【发布时间】: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