在 Javascript 中模拟鼠标单击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20602297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:51:20  来源:igfitidea点击:

Simulate a mouse-click in Javascript

javascript

提问by zyl1647

Looking for a Javascript that do a left-mouse click on a image/button identified by ID or CLASS name, wait x seconds and repeat. And able to run in developer tools Console tap, in chrome and firefox.

寻找在由 ID 或 CLASS 名称标识的图像/按钮上单击鼠标左键的 Javascript,等待 x 秒并重复。并且能够在开发者工具 Console tap、chrome 和 firefox 中运行。

Tried to write it myself, cause i figured it would be a simple code, but after 2 hours of trial and error with no luck, i am starting to run out of options.

试图自己编写它,因为我认为这将是一个简单的代码,但是经过 2 个小时的反复试验但没有运气,我开始没有选择了。

Hopefully a Javascript pro out there got time to help out a very novice user ;)

希望 Javascript 专家有时间帮助一个非常新手的用户 ;)

Thanks

谢谢

回答by scrblnrd3

If you're willing to use jQuery, you can use this simple function to do it:

如果你愿意使用 jQuery,你可以使用这个简单的函数来做到这一点:

window.setInterval(function(){
    $("#divToClick").trigger("click");
}, 1000);

That will call it every 1000 milliseconds, or 1 second

这将每 1000 毫秒或 1 秒调用一次

For a pure Javascript solution, you should take a look at How to trigger event in Javascript

对于纯 Javascript 解决方案,您应该查看如何在 Javascript 中触发事件

or, if you're not interested in supporting IE, you can do it the simple way, with an Event()constructor, and event.dispatch()

或者,如果你对支持 IE 不感兴趣,你可以用一个简单的方法,用一个Event()构造函数,然后event.dispatch()

回答by Diego Carrion

What's wrong with

怎么了

document.getElementById(id).click()

回答by adeneo

You'd use the event constructorand dispatchEventfor that :

您将使用事件构造函数dispatchEvent为此:

var support = true; // check if event constructor is supported

try {
    if (new MouseEvent('click', {bubbles: false}).bubbles !== false) {
        support = false;
    } else if (new MouseEvent('click', {bubbles: true}).bubbles !== true) {
        support = false;
    }
} catch (e) {
    support = false;
}

setInterval(function() {
    if (support) {
        var event = new MouseEvent('click');
    }else{
        var event = document.createEvent('Event');
        event.initEvent('click', true, true);
    }
    elem.dispatchEvent(event);
},1000);

FIDDLE

小提琴