首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果在元素上触发CustomEvent,则取消“Click”DOM事件

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

Stack Overflow用户
提问于 2019-05-21 10:14:49
回答 3查看 186关注 0票数 0

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

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

我有一个元素,我想同时设置一个‘点击’监听器和一个‘长按’监听器,类似于许多移动应用程序,比如相册或电子邮件,它们在点击和长按事件之间的反应是不同的。

long-press事件确实会触发,但“Click”事件每次都会触发,我找不到应该如何或何时尝试阻止它触发。我已经尝试了stopDefault()stopPropogation()的几个位置,但都没有用。

带有监听器的HTML是

代码语言:javascript
复制
<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或长按公文包图像时

代码语言:javascript
复制
$(document).on('long-press', '.portfolio-img', (e) => {
    e.preventDefault();
    e.stopPropagation();
    console.log('Portfolio long press event.');
 });
$(document).on('click', '.lightbox-img', imageClick);

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-05-21 11:03:15

要做到这一点,一种方法是从触发long-press事件的那一刻起,直到文档上的下一个mouseup事件触发,从clicked元素中禁用pointer-events

最好的方法可能是从你的库中创建它,所以这里是这个库的一个分支,它现在在CustomEvent上公开了一个preventDefaultClick()方法:

代码语言:javascript
复制
(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
});
代码语言:javascript
复制
<button data-long-press-delay="500" id="btn">click me</button>

但如果像我一样,你有一个每次滑动都会触发一系列事件的鼠标,那么你可能更喜欢这个演示,其中轮子等超时触发器已被禁用:

代码语言:javascript
复制
(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
});
代码语言:javascript
复制
<button data-long-press-delay="500" id="btn">click me</button>

票数 1
EN

Stack Overflow用户

发布于 2019-05-21 10:23:57

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

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

代码语言:javascript
复制
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;
});

我注释掉了这几行...

代码语言:javascript
复制
e.preventDefault();
e.stopPropagation();

因为我相信它们只是在您试图阻止click事件处理程序触发时才出现的。

票数 0
EN

Stack Overflow用户

发布于 2019-05-21 10:34:51

您可以使用布尔值以及mousedownmouseup侦听器

代码语言:javascript
复制
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');
}
代码语言:javascript
复制
#ele {
  background: black;
  width: 100px;
  height: 20px;
  color: white;
  cursor: pointer;
}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ele">Click Here</div>

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56230245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档