我在这里有一个演示
我有一个由块组成的酒吧,上面有一个标记和一个输入字段
在输入字段中输入数字会将标记滑至该百分比
当标记位于该块上方时,块应更改颜色。
这可以工作,但是只有在标记移至另一个块或再次单击Enter后,这些块才会更改颜色。
当标记移到该块时,为什么块不改变颜色。
const marker = document.querySelector('.bar-marker');
const bars = document.querySelectorAll('.bar-item');
const input = document.querySelector('.value');
(function() {
input.addEventListener("keyup", (event) => {
event.preventDefault();
if (event.keyCode === 13) {
const inputVal = document.querySelector('.value').value;
moveBar(inputVal)
}
})
function moveBar(val){
marker.style.left = val + '%';
for(let i=0; i<=bars.length; i++){
bars[i].classList.remove('selected')
if(marker.offsetLeft >
bars[i].offsetLeft && marker.offsetLeft <
bars[i].offsetWidth+bars[i].offsetLeft){
bars[i].classList.add('selected')
}
}
}
})();
这是因为您有一个2s animation
滑块的过渡,这意味着marker.offsetLeft
将具有到达起点的滑块起点值2s delay
。解决方案是等待2s
动画结束,然后运行脚本。
使用setTimeout
2.1s可能有效。
function moveBar(val){
marker.style.left = val + '%';
setTimeout(function(){
for(let i=0; i<=bars.length; i++){
bars[i].classList.remove('selected')
if(marker.offsetLeft >
bars[i].offsetLeft && marker.offsetLeft <
bars[i].offsetWidth+bars[i].offsetLeft){
bars[i].classList.add('selected')
}
}
}, 2100);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句