我正在使用滑动效果滑动器。我正在使用Wes Bos的Youtube教程中的示例。问题是当我单击父项(mousedown事件)时,它也会在mouseup事件之后触发子事件。
我试图添加一个计时器,该计时器允许在mouseup事件完成几秒钟后在子元素上单击事件。
HTML:
<div class="items">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
</div>
CSS:
.items {
height: 300px;
overflow: scroll;
}
.items .item {
width: 200px;
height: 80px;
background: green;
border-bottom: 1px solid red;
}
Javascript:
let clickNotAllowed = false;
// ------------------- Tutorial ------------------- //
const slider = document.getElementsByClassName('items')[0];
let isDown = false;
let startY;
let scrollTop;
let speed = 0.5;
// Mouse down will trigger the parent event (swipe), but also the child event will
// be added to the list of events which need to be executed
slider.addEventListener('mousedown', (e) => {
isDown = true;
startY = e.pageY - slider.offsetTop;
scrollTop = slider.scrollTop;
});
slider.addEventListener('mouseleave', () => {
isDown = false;
clickNotAllowed = false;
});
slider.addEventListener('mouseup', () => {
isDown = false;
// Not part of the tutorial
// I tried to set the timer so a few ms after the mouse is up
// I'm setting the clickNotAllowed to true so the user will be able to click
// Before this timer is finished, click event on the child will try to execute itself
setTimeout(function() {
clickNotAllowed = false;
}, 200);
});
slider.addEventListener('mousemove', (e) => {
if(!isDown) return;
e.preventDefault();
const x = e.pageY - slider.offsetTop;
const walk = (x - startY) * speed;
slider.scrollTop = scrollTop - walk;
// --- Not part of tutorial --- //
clickNotAllowed = true;
});
// ============= NOT PART OF THE TUTORIAL ============= //
const item = document.getElementsByClassName("item");
for(let i = 0; i < item.length; i++) {
item[i].addEventListener("click", function(e) {
if(clickNotAllowed) return;
e.target.style.background = "blue";
});
}
预期结果是当我单击父级(滑块-items类)并且触发mousedown事件时,在执行父级元素的mouseup之后不应执行子级事件。