使用 javascript 保持事件 [英] Hold event with javascript

查看:20
本文介绍了使用 javascript 保持事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很想知道当您点击(在移动设备上)或点击(在桌面设备上)表单提交/锚定/等时,是否有任何方法可以执行某个功能.并在不使用 jQuery 的情况下保持一段时间!

function clicked() {//设置某种计时器左右...}函数 toBeExecutedNMillisecondsAfterAnchorWasClicked() {//做一些事情...}

解决方案

(function() {var mouseTimer;函数 mouseDown() {鼠标向上();mouseTimer = window.setTimeout(execMouseDown,2000);//设置超时以在用户按下鼠标按钮时在 2 秒内触发}功能鼠标向上(){if (mouseTimer) window.clearTimeout(mouseTimer);//松开鼠标按钮时取消计时器div.style.backgroundColor = "#FFFFFF";}函数 execMouseDown() {div.style.backgroundColor = "#CFCF00";}var div = document.getElementById("bam");div.addEventListener("mousedown", mouseDown);document.body.addEventListener("mouseup", mouseUp);//监听身体上的鼠标向上事件,而不仅仅是你最初点击的元素}());

#bam { width:100px;高度:100px;边框:1px纯黑色;}

按住鼠标按钮 2 秒钟.

<p>培根</p><p>培根</p><p>培根</p><p>培根</p><p>培根</p><p>培根</p><p>培根</p><p>培根</p><p>培根</p>

I really would like to know if there is any way to execute a function when you tap (on mobile device) or click (on desktop device) a form submit/anchor/etc. and hold it for some amount of time WITHOUT using jQuery!

function clicked() {
    //set some kind of timer or so...
}

function toBeExecutedNMillisecondsAfterAnchorWasClicked() {
     //do some stuff...
}

解决方案

(function() {

  var mouseTimer;
  function mouseDown() { 
      mouseUp();
      mouseTimer = window.setTimeout(execMouseDown,2000); //set timeout to fire in 2 seconds when the user presses mouse button down
  }

  function mouseUp() { 
      if (mouseTimer) window.clearTimeout(mouseTimer);  //cancel timer when mouse button is released
      div.style.backgroundColor = "#FFFFFF";
  }

  function execMouseDown() { 
      div.style.backgroundColor = "#CFCF00";
  }

  var div = document.getElementById("bam");
  div.addEventListener("mousedown", mouseDown);
  document.body.addEventListener("mouseup", mouseUp);  //listen for mouse up event on body, not just the element you originally clicked on
  
}());

#bam { width:100px; height: 100px; border: 1px solid black; }

<div id="bam"> Hold mouse button for 2 seconds. </div>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>

这篇关于使用 javascript 保持事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆