var movePixel=300, maxContent=5, displayContent=3, timer; $(".left-arrow").on("click",function(){ doCarousel("left") }); $(".right-arrow").on("click",function(){ doCarousel("right") }); function doCarousel(type){ var imgContent= $(".img-content"), calString=type=="left"?"-=":"+="; if(!isValidMove(type)){ shiftImg(imgContent,type); }else{ $(imgContent).animate({ marginLeft: calString+movePixel+"px" }); } } function shiftImg(imgContent,type){ if(type=="left"){ var item=$(imgContent).find(".img-frame:eq(0)"), nowMarginLeft=parseInt($(".img-content").css("marginLeft").replace('px', '')); $(imgContent).css("marginLeft",(parseInt($(".img-content").css("marginLeft").replace('px', ''))+movePixel)+"px"); item.remove(); $(imgContent).append(item); $(imgContent).animate({ marginLeft: nowMarginLeft+"px" }); }else{ var item=$(imgContent).find(".img-frame:last"), nowMarginLeft=parseInt($(".img-content").css("marginLeft").replace('px', '')); $(imgContent).css("marginLeft",(parseInt($(".img-content").css("marginLeft").replace('px', ''))-movePixel)+"px"); item.remove(); $(imgContent).prepend(item); $(imgContent).animate({ marginLeft: nowMarginLeft+"px" }); } } function isValidMove(type){ var steps=maxContent-displayContent, nowMarginLeft=parseInt($(".img-content").css("marginLeft").replace('px', '')), result=false; if(typeof(nowMarginLeft)!=="undefined"&&nowMarginLeft!=null){ switch(type){ case "left": nowMarginLeft-=movePixel; nowMarginLeft=Math.abs(nowMarginLeft); if(nowMarginLeft<=steps*movePixel){ result=true; } break; case "right": nowMarginLeft+=movePixel; if(nowMarginLeft<=0){ result=true; } break; } } return result; }
<div class="carousel"> <img class="arrow left-arrow" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTypuI4VcgOYwtJDLtvVqGZ3NGEOUb0hdyqgWbG1u6kgNrbReqXjg"> <div class="show-room"> <div class="img-content"> <div class="img-frame"> <img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSRQe3poGb17DtoGHMC9xYgpVD0TEkjzP4M9umHdoJocAQAEV-R" /> </div> <div class="img-frame"> <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSVmaQ811OtkG0xJoGeecH-2mrcgE3awE0aQJBDK2wDCs6M-sb44w" /> </div> <div class="img-frame"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ-8UzPRXKs9wZcYzszae5AOb3AniGIzRRAR9-53GkocL8dt2zMmw" /> </div> <div class="img-frame"> <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS6focM0uX2CyFwneDSke0xPhrB1g24hHGaw5931Wy00DHqA15U8g" /> </div> <div class="img-frame"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ2ScairUgzqy92-Fac58a7DoNsmMS5S4OxfOEqjT0qaI_ctyBY" /> </div> </div> </div> <img class="arrow right-arrow" src="http://www.netzrocker.com/assets/img/icon_next.png"> </div>
.carousel{ width:990px; } .arrow{ margin-top:120px; float:left; } .show-room { width:930px; overflow:hidden; float:left; } .show-room .img-frame{ width:310px; margin:5px; display:inline; } .img-frame img{ width:300px; } .img-content{ width:2000px; display:block; }