我只是想知道如何使用JavaScript来模拟对元素的单击。
目前我有:
function simulateClick(control) {
if (document.all) {
control.click();
} else {
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
control.dispatchEvent(evObj);
}
}
<a href="http://www.google.com" id="mytest1">test 1</a><br>
<script type="text/javascript">
simulateClick(document.getElementById('mytest1'));
</script>
但它并没有起作用:(
什么好主意吗?
模拟事件类似于创建自定义事件。模拟鼠标事件
我们必须使用document.createEvent()创建MouseEvent。
然后使用initMouseEvent(),我们必须设置将要发生的鼠标事件。
然后在您想要模拟事件的元素上分派鼠标事件。
在下面的代码中,我使用了setTimeout,以便按钮在1秒后自动单击。
const div = document.querySelector('div');
div.addEventListener('click', function(e) {
console.log('Simulated click');
});
const simulatedDivClick = document.createEvent('MouseEvents');
simulatedDivClick.initEvent(
'click', /* Event type */
true, /* bubbles */
true, /* cancelable */
document.defaultView, /* view */
0, /* detail */
0, /* screenx */
0, /* screeny */
0, /* clientx */
0, /* clienty */
false, /* ctrlKey */
false, /* altKey */
false, /* shiftKey */
0, /* metaKey */
null, /* button */
null /* relatedTarget */
);
// Automatically click after 1 second
setTimeout(function() {
div.dispatchEvent(simulatedDivClick);
}, 1000);
<div> Automatically click </div>