上一篇關於圖片輪番效果雖然實現了,但是代碼寫的相對複雜,經過研究測試,項目中使用下面方法實現需求效果
1、顯示頁面效果的代碼,在裏定義輪番的圖片
//imgPathList是圖片集合 有圖片id、圖片地址
<div id="slide" >
<ul>
<c:forEach items="${imgPathList}" var="imgPath">
<li>
<img id="img${imgPath.id}" width="600px" height="400px" src="${ctx}/~/photo/${imgPath.frontpicture}" />
</li>
</c:forEach>
</ul>
<div id="ico" class="ico">
<c:forEach items="${imgPathList}" var="imgPath">
<a id="${imgPath.id}" href="javascript:void(0);" style="display:none">${ctx }/~/photo/${imgPath.frontpicture}</a>
</c:forEach>
</div>
</div>
2、定義輪番圖片的樣式
* {
margin: 0px;
padding: 0px;
}
li {
list-style: none;
}
img {
border: 0;
}
a {
text-decoration: none;
}
#slide {
width: 900px;
height: 500px;
box-shadow: 0px 0px 5px #c1c1c1;
margin: 10px auto;
position: relative;
overflow: hidden;
}
#slide ul {
position: absolute;
left: 0px;
top: 0px;
height: 400px;
width: 11930px;
}
#slide ul li {
width: 1100px;
height: 400px;
overflow: hidden;
float: left;
}
#slide .ico {
width: 800px;
height: 20px;
overflow: hidden;
text-align: center;
position: absolute;
left: 0px;
bottom: 10px;
z-index: 1;
}
#slide .ico a {
display: inline-block;
width: 10px;
height: 10px;
background: url(out.png) no-repeat 0px 0px;
margin: 0px 5px;
}
#slide .ico .active {
background: url(out1.png) no-repeat 0px 0px;
}
3、js實現輪番事件
$(document).ready(function() {
var oIco = document.getElementById("ico");
var aBtn = oIco.getElementsByTagName("a");
var oSlide = document.getElementById("slide");
var oUl = oSlide.getElementsByTagName("ul");
var aLi = oUl[0].getElementsByTagName("li");
var oBtnPrev = document.getElementById("prevBtn");
var oBtnNext = document.getElementById("nextBtn");
var baseWidth = aLi[0].offsetWidth;
oUl[0].style.width = baseWidth * aLi.length + "px";
aBtn[0].className = "active";
var iNow = 0;
//上一頁
oBtnPrev.onclick = function() {
if(iNow==0){
alert("沒有上一張上交的作業了");
}else{
iNow--;
move(iNow);
}
};
//下一頁
oBtnNext.onclick = function() {
iNow++;
if(iNow==aLi.length){
alert("沒有下一張上交的作業了");
iNow=iNow-1;
}else{
move(iNow);
}
};
function move(index) {
if(index > aLi.length - 1) {
index = 0;
iNow = index;
}
if(index < 0) {
index = aLi.length - 1;
iNow = index;
}
for(var n = 0; n < aBtn.length; n++) {
aBtn[n].className = "";
}
aBtn[index].className = "active";
oUl[0].style.left = -index * baseWidth + "px";
}
});