【问题标题】:Add delay to mousemove event为 mousemove 事件添加延迟
【发布时间】:2019-10-28 21:24:24
【问题描述】:

我在 mousemove 事件上运行此函数。该功能是迭代图像列表并一次移动到顶部(z-index)。这工作正常,但我的问题是脚本运行得非常快,图像显示得非常快。如何为函数或事件添加延迟?我尝试使用 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>

【问题讨论】:

  • 我建议不要使用鼠标移动事件,onmouseenter 和 onmouseleave 更容易控制,对性能影响更小

标签: javascript events mousemove


【解决方案1】:

使用Debounce

这样的事情应该可以工作(从changeBkg内部删除超时):

//change 300ms to suite your needs
<section class="main" onmousemove="debounce(changeBkg(event),300)"></section>

去抖动是一个高阶函数,它是一个返回另一个函数的函数。这样做是为了在 func 、 wait 和 immediate 函数参数以及 timeout 变量周围形成一个闭包,以便保留它们的值。

进一步阅读/如果您更喜欢自己实现:Debounce Article

【讨论】:

    【解决方案2】:

    已经解决了。 因为我需要的是某种动画,所以我用greensock想出来了 所以我的事件在这个动画里面有触发,当 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' )
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      • 2014-03-18
      • 2014-10-21
      相关资源
      最近更新 更多