js自定义"longPress"长按事件

<html>
  <head>
   <script>
  function enableLongPress(target, threshold) {
   var timer;
   var timeOut;
   var evt = document.createEvent('Event');
   evt.initEvent('longpress', true, true);
   target.addEventListener('mousedown', function() {
      timer = Date.now();
      timeOut=setTimeout(function(){
        target.dispatchEvent(evt);
      },threshold);
   }, false);
   target.addEventListener('mouseup', function() {
      if(Date.now() - timer < threshold) {
         evt.duration = Date.now() - timer;
         clearTimeout(timeOut);
      }
   }, false);
 }
</script>
</head>
<body>
    <input type="button" name="xx" id="btn1" value="btn1" />
    <script>
        var button=document.getElementById("btn1");
            enableLongPress(button, 1000);
            button.addEventListener('longpress', function(e) {
            alert("longpress");
            console.log('Pressed for ' + e.duration + ' milliseconds.');
         }, false);
    </script>
</body>
</html>

你可能感兴趣的:(js自定义"longPress"长按事件)