页面加载时也会执行滚动功能

时间:2016-07-14 06:05:17

标签: javascript jquery html css events

我做了jsfiddle作为How to build fullscreen slider like this?(现在暂停)的答案 我知道滚动速度太快,而且滚动两种方式都做同样的事情,但我的问题是当页面加载时,它会自动滚动一次 我使用的代码是

var leftImg = document.getElementsByClassName('left');
var rightImg = document.getElementsByClassName('right');
var cur = 0;
for (i=0; i<3; i++){
    leftImg[i].style.zIndex = rightImg[i].style.zIndex = -(i+1);
}

window.onmousewheel = changeImage();

function changeImage() {
  leftImg[cur].style.top= "-100%";
  rightImg[cur].style.top= "100%";
  setTimeout(function(){
    window.onmousewheel = changeImage; 
  leftImg[cur].style.zIndex=rightImg[cur].style.zIndex=-(cur+4);
  leftImg[cur].style.top=rightImg[cur].style.top="0";
  cur++;
  if(cur === 3) {
    cur = 0;
for (i=0; i<3; i++){
    leftImg[i].style.zIndex = rightImg[i].style.zIndex = -(i+1);
}
  }
}, 3000);
  window.onmousewheel = preventDefault;
}  

为什么?

1 个答案:

答案 0 :(得分:0)

已编辑#2

不需要循环也不需要TimeOut

var cur = 2;
var zIndex = -1;

window.onmousewheel = changeImage;
function changeImage() {

    var leftImg = document.getElementsByClassName('left');
    var rightImg = document.getElementsByClassName('right');
    leftImg[cur].style.top = "-100%";
    rightImg[cur].style.top = "100%";
    if (leftImg[(cur + 1) % 3].style.top === "-100%") {
        leftImg[(cur + 1) % 3].style.zIndex = rightImg[(cur + 1) % 3].style.zIndex = (zIndex);
        leftImg[(cur + 1) % 3].style.top = rightImg[(cur + 1) % 3].style.top = "0%";

    }
    zIndex--;
    cur--;
    if (cur === -1) {
        cur = 2;
    }

}

请参阅fiddle