2015-06-06 110 views
4

我只是做了一個非常簡單的「imageslider」,但它不滑動,所以我們稱之爲「imageswapper」。交換圖像

好的。我的問題是現在,我怎樣才能讓它滑入並滑出來,這樣就順利了。

JSFIDDLE

[JS]

document.getElementById('atwo').style.display = "none"; 
    function ImgSwap(){ 
     if(document.getElementById('one').style.display == "block"){ 
     document.getElementById('one').style.display = "none"; 
     document.getElementById('two').style.display = "block"; 
     }else{ 
     document.getElementById('two').style.display = "none"; 
     document.getElementById('one').style.display = "block"; 
     } 
    } 

[HTML]

<div id="wrapper"> 
<a onclick="ImgSwap()" id="aone"><img src="one.jpg" alt="one" class="img" id="one" /></a> 
<a onclick="ImgSwap()" id="atwo"><img src="two.gif" alt="two" class="img" id="two" /></a> 
</div> 

[CSS]

 img.img 
    { 
     height: 200px; 
     width: 300px; 
    } 
    #one 
    { 
     display: block; 
    } 
    #two 
    { 
     display:none; 
    } 
    a:hover 
    { 
     cursor: pointer; 
    } 
    div#wrapper 
    { 
     width: 300px; 
    } 
+0

使用[jQuery的](http://jquery.com/),這變得微不足道。 –

回答

3

有很多種方法來實現這一效果,一個方法這是通過一個將css轉換到你的css類。您可以更改圖像的不透明度和位置以創建有效的幻燈片。

function ImgSwap() { 
 
    document.getElementById('one').classList.toggle('show'); 
 
    document.getElementById('two').classList.toggle('show'); 
 
}
div#wrapper { 
 
    width: 300px; 
 
    height: 200px; 
 
    position: relative; 
 
    background-color: black; 
 
} 
 
.img { 
 
    height: 200px; 
 
    width: 300px; 
 
    position: absolute; 
 
    top: 0; 
 
    left: -300px; 
 
    opacity: 0; 
 
} 
 
a:hover { 
 
    cursor: pointer; 
 
} 
 
.show { 
 
    left: 0; 
 
    opacity: 1; 
 
    transition: left 1s; 
 
}
<div id="wrapper"> 
 
    <a onclick="ImgSwap()" id="aone"> 
 
    <img src="https://c2.staticflickr.com/6/5120/5824578555_d239d42195_b.jpg" alt="one" class="img show" id="one" /> 
 
    </a> 
 
    <a onclick="ImgSwap()" id="atwo"> 
 
    <img src="http://petsadviser.supercopyeditors.netdna-cdn.com/wp-content/uploads/2012/06/why-is-cat-scared-rain-thunder.png" alt="two" class="img" id="two" /> 
 
    </a> 
 
</div>

+0

謝謝艾米,但我該如何改進代碼,以便不會有任何延遲?我發現轉換選擇器是這樣做的,而不是所有的轉換選擇器,我只能針對幻燈片轉換而不是延遲轉換? – SwegreDesigns

+0

@SwegreDesigns,我編輯了上面的代碼。我改變了過渡隻影響左值,我也更新了隱藏的左側位置是圖像的負全寬度值。 – Amy

+0

很好地完成了艾米!非常感謝! – SwegreDesigns