如果CustomEvent在元素上触发,则取消“ Click” DOM事件

时间:2019-05-21 02:14:49

标签: javascript cordova dom dom-events jquery-events

我正在Cordova中构建一个应用程序,并且与许多应用程序一样,我试图实现按住一个元素后发生的长按事件。

我正在使用https://github.com/john-doherty/long-press-event,它在按住一个元素1.5秒后会触发一个名为“长按”的CustomEvent。

我有一个元素想同时启用“点击”监听器和“长按”监听器,类似于许多移动应用(例如照片库或电子邮件),它们在点击和长按之间的反应不同。新闻发布会。

长按事件确实会触发,但是“单击”事件也会在每次触发,并且我找不到应该如何或何时尝试使其停止触发的事件。我已经尝试了stopDefault()stopPropogation()的多个展示位置,但无济于事。

带有侦听器的HTML是

<div class="grid-col grid-col--1">
    <div class="grid-item bd bdrs-4 bdw-1 bdc-grey-400">
        <img class="portfolio-img lightbox-img" src="https://glamsquad.sgp1.cdn.digitaloceanspaces.com/GlamSquad/artist/1/portfolio/2019-05-16-06-07-370bc89b7bfe9769740c1f68f7e103340a94aaaeaa5d6f139f841e3c022ad309de.png">
    </div>
    <div class="grid-item bd bdrs-4 bdw-1 bdc-grey-400">
        <img class="portfolio-img lightbox-img" src="https://glamsquad.sgp1.cdn.digitaloceanspaces.com/GlamSquad/artist/1/portfolio/2019-05-16-06-07-38d8d03cc6edef043d25e9099b883cd235c823a267ab03b9e740934f06c4f87e2f.png">
    </div>
</div>

当JS代码正在侦听lightbox-img的点击或长按投资组合图片时

$(document).on('long-press', '.portfolio-img', (e) => {
    e.preventDefault();
    e.stopPropagation();
    console.log('Portfolio long press event.');
 });
$(document).on('click', '.lightbox-img', imageClick);

有什么实际的方法可以触发长按事件,但可以取消或停止单击事件的发生吗?

3 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是,从触发pointer-events事件的那一刻起,在您单击的元素中禁用long-press,直到在文档上触发下一个mouseup事件为止。 / p>

最好是从您的库中获取它,所以这是该库的一个分支,它现在在CustomEvent上公开了一个preventDefaultClick()方法:

(function (window, document) {

    'use strict';

    var timer = null;

    // check if we're using a touch screen
    var isTouch = (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0));

    // switch to touch events if using a touch screen
    var mouseDown = isTouch ? 'touchstart' : 'mousedown';
    var mouseOut = isTouch ? 'touchcancel' : 'mouseout';
    var mouseUp = isTouch ? 'touchend' : 'mouseup';
    var mouseMove = isTouch ? 'touchmove' : 'mousemove';

    // wheel/scroll events
    var mouseWheel = 'mousewheel';
    var wheel = 'wheel';
    var scrollEvent = 'scroll';

    // patch CustomEvent to allow constructor creation (IE/Chrome)
    if (typeof window.CustomEvent !== 'function') {

        window.CustomEvent = function(event, params) {

            params = params || { bubbles: false, cancelable: false, detail: undefined };

            var evt = document.createEvent('CustomEvent');
            evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
            return evt;
        };

        window.CustomEvent.prototype = window.Event.prototype;
    }

    // listen to mousedown event on any child element of the body
    document.addEventListener(mouseDown, function(e) {
        var el = e.target;
        // get delay from html attribute if it exists, otherwise default to 1500
        var longPressDelayInMs = parseInt(el.getAttribute('data-long-press-delay') || '1500', 10);
        // start the timer
        timer = setTimeout(fireLongPressEvent.bind(el, e), longPressDelayInMs);
    });

    // clear the timeout if the user releases the mouse/touch
    document.addEventListener(mouseUp, function() {
        clearTimeout(timer);
    });

    // clear the timeout if the user leaves the element
    document.addEventListener(mouseOut, function() {
        clearTimeout(timer);
    });

    // clear if the mouse moves
    document.addEventListener(mouseMove, function() {
        clearTimeout(timer);
    });

    // clear if the Wheel event is fired in the element
    document.addEventListener(mouseWheel, function() {
        clearTimeout(timer);
    });

    // clear if the Scroll event is fired in the element
    document.addEventListener(wheel, function() {
        clearTimeout(timer);
    });

    // clear if the Scroll event is fired in the element
    document.addEventListener(scrollEvent, function() {
        clearTimeout(timer);
    });

    /**
     * Fires the 'long-press' event on element
     * @returns {void}
     */
    function fireLongPressEvent() {
        var evt = new CustomEvent('long-press', { bubbles: true, cancelable: true });
        // Expose a method to prevent the incoming click event
        var el = this;
        evt.preventDefaultClick = function() {
          // disable all pointer-events
          el.style["pointer-events"] = "none";
          // reenable at next mouseUp
          document.addEventListener(mouseUp, e => {
            el.style["pointer-events"] = "all";
          }, {once: true});
        };
        // fire the long-press event
        this.dispatchEvent(evt);

        clearTimeout(timer);
    }

}(window, document));

btn.addEventListener('click', e => console.log('clicked'));
btn.addEventListener('long-press', e => {
  console.log('long-press');
  e.preventDefaultClick(); // prevents the incoming 'click' event
});
<button data-long-press-delay="500" id="btn">click me</button>

但是,如果像我一样,您的鼠标在每次滑动时确实触发了一系列事件,那么您可能更喜欢此演示,其中禁用了转轮等超时触发器:

(function (window, document) {

    'use strict';

    var timer = null;

    // check if we're using a touch screen
    var isTouch = (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0));

    // switch to touch events if using a touch screen
    var mouseDown = isTouch ? 'touchstart' : 'mousedown';
    var mouseOut = isTouch ? 'touchcancel' : 'mouseout';
    var mouseUp = isTouch ? 'touchend' : 'mouseup';
    var mouseMove = isTouch ? 'touchmove' : 'mousemove';

    // wheel/scroll events
    var mouseWheel = 'mousewheel';
    var wheel = 'wheel';
    var scrollEvent = 'scroll';

    // patch CustomEvent to allow constructor creation (IE/Chrome)
    if (typeof window.CustomEvent !== 'function') {

        window.CustomEvent = function(event, params) {

            params = params || { bubbles: false, cancelable: false, detail: undefined };

            var evt = document.createEvent('CustomEvent');
            evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
            return evt;
        };

        window.CustomEvent.prototype = window.Event.prototype;
    }

    // listen to mousedown event on any child element of the body
    document.addEventListener(mouseDown, function(e) {
        var el = e.target;
        // get delay from html attribute if it exists, otherwise default to 1500
        var longPressDelayInMs = parseInt(el.getAttribute('data-long-press-delay') || '1500', 10);
        // start the timer
        timer = setTimeout(fireLongPressEvent.bind(el, e), longPressDelayInMs);
    });

    // clear the timeout if the user releases the mouse/touch
    document.addEventListener(mouseUp, function() {
        clearTimeout(timer);
    });

    // clear the timeout if the user leaves the element
    document.addEventListener(mouseOut, function() {
        clearTimeout(timer);
    });

    // clear if the mouse moves
    document.addEventListener(mouseMove, function() {
//        clearTimeout(timer);
    });

    // clear if the Wheel event is fired in the element
    document.addEventListener(mouseWheel, function() {
//        clearTimeout(timer);
    });

    // clear if the Scroll event is fired in the element
    document.addEventListener(wheel, function() {
//        clearTimeout(timer);
    });

    // clear if the Scroll event is fired in the element
    document.addEventListener(scrollEvent, function() {
//        clearTimeout(timer);
    });

    /**
     * Fires the 'long-press' event on element
     * @returns {void}
     */
    function fireLongPressEvent() {
        var evt = new CustomEvent('long-press', { bubbles: true, cancelable: true });
        // Expose a method to prevent the incoming click event
        var el = this;
        evt.preventDefaultClick = function() {
          // disable all pointer-events
          el.style["pointer-events"] = "none";
          // reenable at next mouseUp
          document.addEventListener(mouseUp, e => {
            el.style["pointer-events"] = "all";
          }, {once: true});
        };
        // fire the long-press event
        this.dispatchEvent(evt);

        clearTimeout(timer);
    }

}(window, document));

btn.addEventListener('click', e => console.log('clicked'));
btn.addEventListener('long-press', e => {
  console.log('long-press');
  e.preventDefaultClick(); // prevents the incoming 'click' event
});
<button data-long-press-delay="500" id="btn">click me</button>

答案 1 :(得分:0)

在这里传播不是问题-这是一个事实,即长点击事件和常规点击事件实际上是同一件事,因此它们都会触发。之所以触发它们,是因为您先按下鼠标然后按下鼠标。在这两个事件之间等待时间更长的事实并不能阻止常规点击被触发。

处理此问题的最简单方法是设置一个标志,该标志指示是否已触发长点击事件,例如...

var longClickTriggered = false;

$(document).on('long-press', '.portfolio-img', (e) => {
    longClickTriggered = true;
    //e.preventDefault();   // these 2 lines are probably not needed now
    //e.stopPropagation();
    console.log('Portfolio long press event.');
});

$(document).on('click', '.lightbox-img', (e) => {
    if (!longClickTriggered) {
        imageClick();
    }
    longClickTriggered = false;
});

我评论了这些内容...

e.preventDefault();
e.stopPropagation();

因为我相信它们只是在您尝试阻止点击事件处理程序启动时出现。

答案 2 :(得分:-1)

您可以将布尔值与mousedownmouseup侦听器一起使用

var timeoutId = 0, isHold = false;

$('#ele').on('mousedown', function() {
  timeoutId = setTimeout(onEleHold, 1000);
}).on('mouseup', function() {
  if (!isHold) {
    onEleClick();
  }
  isHold = false;
  clearTimeout(timeoutId);
  timeoutId = 0;
});

function onEleHold() {
  console.log('hold');
  isHold = true;
}

function onEleClick() {
  console.log('click');
}
#ele {
  background: black;
  width: 100px;
  height: 20px;
  color: white;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ele">Click Here</div>