Javascript-设置超时后执行onscroll功能

时间:2016-06-14 09:44:10

标签: javascript html scroll timeout

所以我创建了一个包含三个div的页面,这些div在滚动时变得可见。问题是代码使它们全部同时执行,而我希望它们应该是每个onscroll函数执行之间的时间差异

代码的相关部分 -

HTML

<section id="section2">
    <span id="one" class="classbefore">lol</span>
    <span id="two" class="classbefore">lol</span>
    <span id="three" class="classbefore">lol</span>
</section>

CSS

#section2 > span{
  width: 25%;
  height: 50%;
  position: absolute;
  background: #f00;
  -webkit-transition: all 0.5s ease;
  box-shadow: 1px #000;
}
#section2 > #one{
  margin-left: 10%;
}
#section2 > #two{
  margin-left: 37.5%;
}
#section2 > #three{
  margin-left: 65%;
}
.classbefore{
  opacity: 0;
  margin-top: 18%;
}
.classafter{
  opacity: 1;
  margin-top: 20%;
}

Javascript

window.addEventListener('scroll', function (event) {
    if (window.scrollY > 600) {
    document.getElementById('one').className = "classafter";
  } else {
      document.getElementById('one').className = "classbefore";
  }
}, true);
window.addEventListener('scroll', function (event) {
    if (window.scrollY > 600) {
    document.getElementById('two').className = "classafter";
  } else {
      document.getElementById('two').className = "classbefore";
  }
}, true);
window.addEventListener('scroll', function (event) {
    if (window.scrollY > 600) {
    document.getElementById('three').className = "classafter";
  } else {
      document.getElementById('three').className = "classbefore";
  }
}, true);

因此,使用此功能,所有三个跨度都可以同时显示。请建议一种方法,让它们超时,以便一个函数在另一个之后执行。

此外,这段代码可以提高效率吗?

1 个答案:

答案 0 :(得分:1)

我认为你打算在同一卷轴之后的不同时间展示它们。那么这个怎么样?

window.addEventListener('scroll', function (event) {
if (window.scrollY > 600) {

    var waitTime = 1000; //base time for showing (in miliseconds)
    setTimeout(function () {
        document.getElementById('one').className = "classafter";
    },waitTime);
    setTimeout(function () { //We  add time to the others waitings
        document.getElementById('two').className = "classafter";
    },waitTime + 100);
    setTimeout(function () {
        document.getElementById('three').className = "classafter";
    },waitTime + 200);
} else {
    document.getElementById('one').className = "classbefore";
    document.getElementById('two').className = "classbefore";
    document.getElementById('three').className = "classbefore";
}
}, true);

CODE NOT TESTED !!

另外,因为它是同一个事件,你只需要一个事件监听器,而不是3.但是那个监听器会在不同的时间改变元素的类

如果使用循环迭代元素会更好:

window.addEventListener('scroll', function (event) {
var elements = document.getElementsByName("commonName");
if (window.scrollY > 600) {
    var waitTime = 1000;//base time for showing (in miliseconds)
    for (var i = 0; i < elements.length; i++) {
        setTimeout(function () {
            elements[i].className = "classafter";
        }waitTime + i * 100);
    }
} else {
    for (var i = 0; i < elements.length; i++) {
        elements[i].className = "classafter";
    }
}
}, true);

CODE NOT TESTED !!

然后它对N个元素

有效