为了账号安全,请及时绑定邮箱和手机立即绑定

如何模拟按住按钮类的点击

如何模拟按住按钮类的点击

慕少森 2023-03-24 16:13:34
我如何模拟按住单击按钮?我可以在哪里elements.[0].click();模拟点击,我怎样才能让它按住按钮例如 5 秒钟而不是放开它?示例代码<!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>
查看完整描述

1 回答

?
跃然一笑

TA贡献1826条经验 获得超6个赞

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

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

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

document.getElementById("button").addEventListener('mousedown', mouseDown);

document.getElementById("button").addEventListener('mouseup', 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, eventName){

  let event;

  if (window.MouseEvent && typeof window.MouseEvent === 'function') {

    event = new MouseEvent(eventName);

  } else {

    event = document.createEvent('MouseEvent');

    event.initMouseEvent(eventName);

  }


  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>


查看完整回答
反对 回复 2023-03-24
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信