所以我正在创建一个包含三个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%;
}
爪哇语
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);
因此,使用它,所有三个跨度同时变得可见。请建议一种方法来给他们超时,以便一个函数在另一个函数之后执行。
另外,可以提高此代码的效率吗?
我以为你的意思是在同一卷轴之后的不同时间显示它们。那么这个呢?
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);
代码未测试!!
此外,由于它是同一事件,因此只需要一个事件侦听器,而不是 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);
代码未测试!!
那么它将对 N 个元素有效