2017-05-06 62 views
-3

替換圖像我有這兩個圖像如何與其他的onclick

#image1{ 
    position:absolute; 
    left:29%; 
    top:40%; 
    background-image: url("../imgdrag/activity1.png"); 
    width:63px; 
    height:38px; 
} 
#image2{ 
    position:absolute; 
    left:29%; 
    top:40%; 
    background-image: url("../imgdrag/activity1red.png"); 
    width:63px; 
    height:38px; 
} 

的這些特點我如何可以替換的圖像2的圖像1,當我點擊一個按鈕使用功能

+0

任何HTML代碼嗎? – Leguest

+0

什麼的JavaScript/JQuery的你試過嗎? –

回答

0
//this with kquery 
$("#button").click(function(){ 
     $('#image1').attr('id', '#image2'); 
    }); 

function change(){ 
document.getElementById('#image1').setAttribute('id', '#image2'); 
} 
0

的與jQuery

$('.replace').click(function(){ 
 
    
 
    $('.image-holder').toggleClass('active'); 
 

 
})
#image1{ 
 
    position:absolute; 
 
    left:29%; 
 
    top:40%; 
 
    background-image: url("../imgdrag/activity1.png"); 
 
    width:63px; 
 
    height:38px; 
 
    z-index: 2; 
 
    background-color: blue; 
 
} 
 
#image2{ 
 
    position:absolute; 
 
    left:29%; 
 
    top:40%; 
 
    background-image: url("../imgdrag/activity1red.png"); 
 
    width:63px; 
 
    height:38px; 
 
    z-index: 1; 
 
    background-color: red; 
 
} 
 
.image-holder { 
 
position: relative; 
 
} 
 
.image-holder.active #image2{ 
 

 
    z-index: 3; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button class="replace">Replace</button> 
 

 
<div class="image-holder"> 
 

 
<div id="image1"></div> 
 
<div id="image2"></div> 
 

 
</div>
切換狀態例

0

我會建議爲你的CSS改變

 

    #image1 { 
     position:absolute; 
     left:29%; 
     top:40%; 
     background-image: url("../imgdrag/activity1.png"); 
     width:63px; 
     height:38px; 
    } 

    #image1.active { 
     background-image: url("../imgdrag/activity1red.png"); 
    } 

那麼,如果你使用jQuery只需添加新的「主動」類,記得首先要檢查它是否已經擁有它。

 

    $('button').on('click', function(e) { 
     var img = $('#image1'); 
     if (!img.hasClass('active')) { 
     img.addClass('active'); 
     } 
    });