2 回答
TA贡献1829条经验 获得超4个赞
您可以通过注册与您的和事件侦听器click共享moved变量的事件侦听器,有条件地防止在滑块上触发单击事件。mousedownmousemove
该{ passive: true }选项表示侦听器不调用event.preventDefault(),并且节省了大量 CPU 时间,特别是对于mousemove每秒可以触发多次的事件。
该true参数指示在事件开始从目标元素冒泡之前应调用事件侦听器。这允许它甚至可以防止传播到已经添加到同一元素上的侦听器,只要它们也没有设置useCapture为true.
const slider = document.querySelector('input[type="range"]');
// prevent this if mousemove occurred between mousedown and mouseup
slider.addEventListener('click', () => {
console.log('click event fired on slider');
});
// fires just before click event
slider.addEventListener('mouseup', () => {
console.log('mouseup event fired on slider');
});
let moved = false;
// reset for each potential click
slider.addEventListener('mousedown', () => {
moved = false;
});
// indicate cancellation should occur for click
slider.addEventListener('mousemove', () => {
moved = true;
}, { passive: true });
// prevents click event if mousemove occurred between mousedown and mouseup
slider.addEventListener('click', event => {
if (moved) {
event.preventDefault();
event.stopImmediatePropagation();
}
}, true);
<input type="range" />
TA贡献1868条经验 获得超4个赞
您应该删除包含event.preventDefault();.
为此,您必须将函数引用保存到一个变量中,如下所示:
const preventClickHandler = (e) => e.preventDefault;
slider.addEventListener('mouseup', () => {
isDown = false;
// Disable click event (for ever unfortunately)
if(moved === true) {
this.addEventListener('click', preventClickHandler);
} else {
this.removeEventListener('click', preventClickHandler);
}
})
添加回答
举报