0
我在做一個使用JavaScript的旋轉木馬示例。有SetInterval做輪播。兩個類似的片段,一個是正確的,另一個是錯誤的。爲什麼?
index++;
index == imgList.length && (index = 0);
show(index);
和
index++;
show(index);
index == imgList.length - 1 && (index = -1);
因爲上面的代碼可以工作,下面的代碼不能有什麼區別。 這裏是所有代碼:
window.onload = function() {
var numList = document.getElementById("numbers").getElementsByTagName("li");
var imgList = document.getElementById("imgs").getElementsByTagName("li");
var containBox = document.getElementById("box");
var index = 0;
var timer = play = null;
for (var i = 0; i < numList.length; i++) {
numList[i].index = i;
numList[i].onmouseover = function() {
clearInterval(timer);
show(this.index);
};
}
function show(a) {
index = a;
var opacity = 0;
for (var i = 0; i < imgList.length; i++) {
imgList[i].style.opacity = 0;
}
for (var i = 0; i < numList.length; i++) numList[i].className = "";
numList[index].className = "current";
timer = setInterval(function() {
opacity += 2;
imgList[index].style.opacity = opacity/100;
opacity == 100 && clearTimeout(timer);
}, 20);
}
function autoPlay() {
play = setInterval(function() {
index++;
show(index);
index == imgList.length - 1 && (index = -1);
// index++;
// index == imgList.length && (index = 0);
// show(index);
}, 2000);
}
autoPlay();
containBox.onmouseover = function() {
clearInterval(play);
}
containBox.onmouseout = function() {
autoPlay();
}
}
#box {
width: 445px;
margin: 0 auto;
position: relative;
}
ul,
li {
padding: 0;
margin: 0;
}
li {
list-style-type: none;
}
#imgs {
position: relative;
}
#imgs li {
position: absolute;
top: 0;
left: 0;
}
#imgs img {
width: 440px;
height: 220px;
}
#numbers {
position: absolute;
right: 15px;
top: 190px;
}
#numbers li {
display: inline-block;
background-color: #F90;
width: 20px;
height: 20px;
border-radius: 20px;
color: rgb(232, 227, 227);
text-align: center;
font-size: 12px;
line-height: 20px;
}
#numbers .current {
color: white;
background-color: #f60;
}
#imgs li {
opacity: 0;
}
#imgs .current {
opacity: 1;
}
<div id="box">
<ul id="imgs">
<li class="current"><img src="01.jpg" alt="01.jpg">1</li>
<li><img src="02.jpg" alt="02.jpg">2</li>
<li><img src="03.jpg" alt="03.jpg">3</li>
<li><img src="04.jpg" alt="04.jpg">4</li>
<li><img src="05.jpg" alt="05.jpg">5</li>
</ul>
<ul id="numbers">
<li class="current">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
當我下面的代碼,我調試鉻devtools發現,當index
第一線index = a
成爲4,然後得到錯誤。我一直在努力三個小時。救命啊!
當然好了,他們是不同的。如果'index'遞增,使得它的值是數組的長度,那麼在調用'show()'之前,它應該被重置爲零**。 – Pointy
對不起,我是新鮮的。我想通過使用錯誤的代碼,當index == imgList.length - 1,index得到值'-1',然後執行'setInterval()'的函數'再次,'index ++',在調用'show()'之前它可以是'0'。你可以請更詳細一點。 – Lewis