[英]Add delay to mousemove event
我有这个 function 在 mousemove 事件上运行。 该功能是迭代图像列表并一次移动到顶部(z-index)。 这工作正常,但我的问题是脚本运行得非常快,图像显示得非常快。 如何向 function 或事件添加延迟? 我尝试使用 setTimeOut 没有任何积极影响
这是代码
// creating variables
const imgQty = 6;
const holder = document.getElementById('holder')
var counter = 1;
var isMoving = false;
var bgtimeout, imgtimeout;
var bkgImgs = []
// this creates the containers for each img
for (let i = 1; i <= imgQty; i++) {
var newDiv = document.createElement('div');
newDiv.classList.add('background')
newDiv.classList.add(`background--${i}`)
newDiv.setAttribute("style", `background-image: url('imgs/${i}.jpg'); z-index: 0;`);
holder.appendChild(newDiv);
bkgImgs.push(newDiv)
}
//this moves the counter and also hides the images when the mouse is not moving
function changeBkg(e){
counter >= imgQty ? counter = 1 : counter++
holder.classList.add('isActive')
clearTimeout(bgtimeout);
clearTimeout(imgtimeout);
bgtimeout = setTimeout(function(){holder.classList.remove('isActive')}, 150);
moveImgs();
}
// and here is where my issue is, this function is working but not as I expected
function moveImgs(){
for(var i = 0; i < bkgImgs.length; i++){
if(bkgImgs[i].classList.contains(`background--${counter}`)){
bkgImgs[i].style.zIndex = "1";
} else{
bkgImgs[i].style.zIndex = "0";
}
}
}
我的逻辑对吗? 还是我必须重新考虑代码?
该事件在以下部分中触发:
<section class="main" onmousemove="changeBkg(event)"></section>
使用去抖动
像这样的东西应该可以工作(从changeBkg内部删除超时):
//change 300ms to suite your needs
<section class="main" onmousemove="debounce(changeBkg(event),300)"></section>
去抖是一个高阶 function,它是一个 function,它返回另一个 function。 这样做是为了在 func、wait 和 immediate function 参数和 timeout 变量周围形成一个闭包,以便保留它们的值。
进一步阅读/如果您更喜欢自己实现: Debounce Article
已解决。 因为我需要的是某种 animation,所以我使用 greensock 解决了所以我的事件在这个 animation 中,当 animPlay 为真时触发,何时播放仍然为假
if(animPlay){
animPlay = false
var tl = new TimelineMax();
tl.staggerFromTo(bkgImgs, .5, {zIndex:0}, {zIndex:1}, .15, 0)
.set(bkgImgs, {zIndex:0, onComplete:() => animPlay = true}, '+=0' )
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.