如何模拟按住按钮类的点击 [英] How to simulate a hold click on a button class

查看:33
本文介绍了如何模拟按住按钮类的点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何模拟按住按钮的点击?我可以在哪里使用 elements.[0].click(); 来模拟点击,我怎样才能让它按住按钮 5 秒钟而不是让它离开?

How can i simulate a hold click down onto a button? where i can use elements.[0].click(); to simulate a click, how can I make it so that it would hold down the button for e.g 5 seconds instead of just letting it go?

示例代码

<!DOCTYPE html>
<html>
<body>

<button class="button" id="button">You released the mouse button.</p>

<script>
document.getElementById("button").onmousedown = function() {mouseDown()};
document.getElementById("button").onmouseup = function() {mouseUp()};

function mouseDown() {
  document.getElementById("button").innerHTML = "The mouse button is held down.";
}

function mouseUp() {
  document.getElementById("button").innerHTML = "You released the mouse button.";
}
</script>

</body>
</html>

推荐答案

您可以创建事件,当然也可以MouseEvents 自己创建.

You can create events and of cause also MouseEvents yourself.

在现代浏览器中,您只需调用所需事件类型的构造函数即可完成此操作,或者通过调用 document.createEvent('<EventName>')https://developer.mozilla.org/en-US/docs/网页/API/事件

In modern browsers you can just do this by calling the constructor of the needed event type, ore by calling document.createEvent('<EventName>') https://developer.mozilla.org/en-US/docs/Web/API/Event

然后您可以使用 dispatchEvent() 在您喜欢的任何元素上触发此事件https://developer.mozilla.org/de/docs/Web/API/EventTarget/dispatchEvent

You can then trigger this event on any element you like using dispatchEvent() https://developer.mozilla.org/de/docs/Web/API/EventTarget/dispatchEvent

document.getElementById("button").onmousedown = function() {mouseDown()};
document.getElementById("button").onmouseup = function() {mouseUp()};

function mouseDown() {
  document.getElementById("button").innerHTML = "The mouse button is held down.";
}

function mouseUp() {
  document.getElementById("button").innerHTML = "You released the mouse button.";
}


// bind click event on simulate button
document.querySelector('.simulate').addEventListener('click', () => {
  console.log('start');
  simulateMouseEvent(document.getElementById("button"), 'mousedown')
  setTimeout(() => {
    console.log('end');
    simulateMouseEvent(document.getElementById("button"), 'mouseup')
  }, 5000)
})

// capsulate the event trigger stuff
// see: http://youmightnotneedjquery.com/
function simulateMouseEvent(el, event){
  if (window.MouseEvent && typeof window.MouseEvent === 'function') {
    var event = new MouseEvent(event);
  } else {
    var event = document.createEvent('MouseEvent');
    event.initMouseEvent(event);
  }

  el.dispatchEvent(event);
}

<!DOCTYPE html>
<html>
<body>

  <p>
    <button class="button" id="button">You released the mouse button.</button>
  </p>

  <p>
    <button class="simulate">simulate</button>
  </p>

</body>
</html>

这篇关于如何模拟按住按钮类的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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