有什么方法可以恢复 Vanilla JavaScript 中的 preventDefault

我正在尝试创建一个水平滚动容器。在确切的情况下,我需要恢复 e.preventDefault(); 从一个点击。


我尝试了很多选项,在 else 语句中更改 'window.location.href' 似乎是一个不错的选择。但我不知道如何从点击的链接中获取 href。


任何想法都可以帮助实现我的目标。:)


slider.addEventListener('mouseup', () => {

    isDown = false;


    // Disable click event (for ever unfortunately)

    if(moved === true) {

        this.addEventListener('click', (e) => {

            e.preventDefault();

        });

    } else {

        // trying to reset click function

    }


慕田峪9158850
浏览 282回答 2
2回答

浮云间

您可以通过注册与您的和事件侦听器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 mouseupslider.addEventListener('click', () => {&nbsp; console.log('click event fired on slider');});// fires just before click eventslider.addEventListener('mouseup', () => {&nbsp; console.log('mouseup event fired on slider');});let moved = false;// reset for each potential clickslider.addEventListener('mousedown', () => {&nbsp; moved = false;});// indicate cancellation should occur for clickslider.addEventListener('mousemove', () => {&nbsp; moved = true;}, { passive: true });// prevents click event if mousemove occurred between mousedown and mouseupslider.addEventListener('click', event => {&nbsp; if (moved) {&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; event.stopImmediatePropagation();&nbsp; }}, true);<input type="range" />

MYYA

您应该删除包含event.preventDefault();.为此,您必须将函数引用保存到一个变量中,如下所示:const preventClickHandler = (e) => e.preventDefault;slider.addEventListener('mouseup', () => {&nbsp; &nbsp; isDown = false;&nbsp; &nbsp; // Disable click event (for ever unfortunately)&nbsp; &nbsp; if(moved === true) {&nbsp; &nbsp; &nbsp; &nbsp; this.addEventListener('click', preventClickHandler);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; this.removeEventListener('click', preventClickHandler);&nbsp; &nbsp; }})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript