有什么方法可以还原Vanilla JavaScript中的preventDefault方法?

时间:2019-10-07 14:29:08

标签: 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
    }

2 个答案:

答案 0 :(得分:1)

您可以通过注册clickmoved事件侦听器共享mousedown变量的mousemove事件侦听器来有条件地防止单击事件在滑块上触发。

{ 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" />

答案 1 :(得分:-1)

您应该删除包含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);
    }
})