Home > Web Front-end > JS Tutorial > body text

Implementation of JS mouse click event

巴扎黑
Release: 2018-05-15 17:01:55
Original
5411 people have browsed it

This article mainly introduces the implementation and expansion ideas of JS mouse 3 click events. Friends who need it can refer to it.

In the past few days, I have read the content related to Dom events in JavaScript advanced programming. At the same time I saw multiple mouse click events on the Internet. Mouse events are one of the simple and commonly used events, so I made some small extensions and implementations for click events to enhance our understanding of Dom events. The implementation and ideas are summarized by myself. If there is anything wrong, please ask the experts to share and correct me.

1. Make a general event processing module (native implementation)

The following implementation is based on the AMD definition module method:

/**
 * 浏览器兼容事件处理组件
 */
define(function () {
  var EventUtil = {
    // 添加事件监听
    addHandler: function (element, type, handler) {
      if (element.addEventListener) {
        element.addEventListener(type, handler, false);// DOM2级事件
      } else if (element.attachEvent) {
        element.attachEvent('on' + type, handler);// DOM2级IE事件
      } else {
        element['on' + type] = handler;// DOM0级事件
      }
    },
    // 移除事件监听
    removeHandler: function (element, type, handler) {
      if (element.removeEventListener) {
        element.removeEventListener(type, handler, false);
      } else if (element.detachEvent) {
        element.detachEvent('on' + type, handler);
      } else {
        element['on' + type] = null;
      }
    },
    // 获取事件对象
    getEvent: function (event) {
      return event ? event : window.event;
    },
    // 获取事件的目标元素
    getTarget: function (event) {
      return event.target || event.srcElement;
    },
    // 禁止事件默认行为
    preventDefault: function (event) {
      if (event.preventDefault) {
        event.preventDefault();
      } else {
        event.returnValue = false;
      }
    },
    // 禁止事件冒泡
    stopPropagation: function (event) {
      if (event.stopPropagation) {
        event.stopPropagation();
      } else {
        event.cancelBubble = true;
      }
    }
  };

  return EventUtil;
});
Copy after login

2 , Mouse 3-click event implementation

Events involved in the mouse click event and execution trigger sequence:

mousedown: Triggered when any mouse button is pressed

mouseup: Release

click is triggered when the mouse button is pressed: click

mousedown

mouseup

dblclick: double-click

Obviously, click depends on dblclick , you can consider implementing three consecutive mouse clicks to trigger execution based on these two events. Design to monitor the click event after triggering dblclick. If the click event is triggered in a short period of time, it will constitute the effect of three consecutive mouse clicks. The specific implementation is as follows: source code:

<p> 
  <button id="button">鼠标3击</button> 
</p>
Copy after login

js code

require([&#39;eventUtil&#39;], function (EventUtil) {
  var button = document.getElementById(&#39;button&#39;);

  click3Event(button, function (event) {
    console.log(&#39;3 click&#39;);
  });

  // 鼠标3击事件
  function click3Event(dom, fn) {
    var handler = function (event) {
      var event = EventUtil.getEvent(event),
        target = EventUtil.getTarget(event);

      var handler = function (event) {
        var event = EventUtil.getEvent(event),
          target = EventUtil.getTarget(event);

        EventUtil.removeHandler(target, &#39;click&#39;, handler);

        // 执行内容
        fn();
      };

      EventUtil.addHandler(target, &#39;click&#39;, handler);

      // 为防止双击后较长时间再次单击执行事件
      setTimeout(function () {
        EventUtil.removeHandler(target, &#39;click&#39;, handler);
      }, 300);
    };

    EventUtil.addHandler(dom, &#39;dblclick&#39;, handler);
  }
Copy after login

3. Implementation of mouse n-click event

Associated from the mouse 3-click event, if n mouse consecutive clicks are realized How to implement event triggering. The idea that comes to mind is: disable the dblclick event of the target object, and only use the click event for logical judgment and operation of continuous clicks. If n clicks are met within a short period of time, execution will be triggered, otherwise the cumulative number will be recalculated. The specific implementation code is as follows:

require([&#39;eventUtil&#39;], function (EventUtil) {
  var button = document.getElementById(&#39;button&#39;);

  nclickEvent(4, button, function (event, n) {
    console.log(n + &#39; click&#39;);
  });


  function nclickEvent (n, dom, fn) {
    // 禁止双击事件
    EventUtil.removeHandler(dom, &#39;dblclick&#39;, null);

    var n = parseInt(n) < 1 ? 1 : parseInt(n),
      count = 0,
      lastTime = 0;

    var handler = function (event) {
      var currentTime = new Date().getTime();

      count = (currentTime - lastTime < 300) ? count + 1 : 0;

      lastTime = new Date().getTime();

      if (count >= n - 1) {
        fn(event, n);
        count = 0;
      }
    };

    EventUtil.addHandler(dom, &#39;click&#39;, handler);
  }
});
Copy after login

Finally, I will share with you a jquery version of the code

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
<p id="box">234234234234234</p>
	<script src="js/jquery.min.js"></script>
	<script>
	(function(){
		var num=0,d=null;
		$(&#39;#box&#39;).click(function(){
			if(d){clearTimeout(d)}
			d=setTimeout(function(){
				num=0
			},200);
			num++;
			if(num>=3){
				alert(num+"\n ok")
			}
		})
	})();
	</script>
</body>
</html>
Copy after login

This article ends. You can choose the code you want to use according to your needs.

The above is the detailed content of Implementation of JS mouse click event. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template