使用javascript以编程方式单击非按钮元素? [英] Programmatically click on a non-button element using javascript?

查看:60
本文介绍了使用javascript以编程方式单击非按钮元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用javascript以编程方式单击非按钮元素?或者至少在Firefox和Chrome等浏览器中是否可以?

How to programmatically click on a non-button element using javascript? Or is it atleast possible in browsers like Firefox and Chrome?

推荐答案

信不信由你,对于一个相当基本的点击,你可以只需在上点击(但更多信息如下):实例 | 直播资源

Believe it or not, for a fairly basic click, you can just call click on it (but more below): Live Example | Live Source

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Artificial Click</title>
</head>
<body>
  <div id="foo">xxxxxxx</div>
  <script>
    (function() {
      var foo = document.getElementById("foo");
      foo.addEventListener("click", function() {
        display("Clicked");
      }, false);
      setTimeout(function() {
        display("Artificial click:");
        foo.click(); // <==================== The artificial click
      }, 500);
      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>

您还可以创建相关类型的事件对象和使用 dispatchEvent 将其发送到元素:

You can also create the relevant type of Event object and use dispatchEvent to send it to the element:

var e = new MouseEvent("click", {
  view: window,
  bubbles: true,
  cancelable: true
});
foo.dispatchEvent(e);

这使您有机会做其他信息(典型的)您正在模拟的事件上的pageX pageY

This gives you the opportunity to do things like set other information (the typical pageX and pageY, for instance) on the event you're simulating.

有关第5节中各种事件对象类型的更多信息DOM事件规范。

More about the various event object types in Section 5 of the DOM Events spec.

这篇关于使用javascript以编程方式单击非按钮元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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