我想模拟整个点击,而不仅仅是
document.getElementsByClassName()[0].click();
我怎么做?搜索结果似乎都是关于处理此类事件,而不是触发它们。
我想模拟整个点击,而不仅仅是
document.getElementsByClassName()[0].click();
我怎么做?搜索结果似乎都是关于处理此类事件,而不是触发它们。
发送鼠标事件。像这样:
//--- Get the first link that has "stackoverflow" in its URL.
var targetNode = document.querySelector ("a[href*='stackoverflow']");
if (targetNode) {
//--- Simulate a natural mouse-click sequence.
triggerMouseEvent (targetNode, "mouseover");
triggerMouseEvent (targetNode, "mousedown");
triggerMouseEvent (targetNode, "mouseup");
triggerMouseEvent (targetNode, "click");
}
else
console.log ("*** Target node not found!");
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
如果网页是静态加载的,这会起作用。如果网页是 AJAX 驱动的,请使用以下技术:
注意:
问题代码有错误。您需要将类名传递给该函数。像这样:
document.getElementsByClassName ("SomeClassName")[0].click();
在Brock 的代码按我的预期工作后,我对其进行了一些改进。
定义:
function simulateMouseClick(targetNode) {
function triggerMouseEvent(targetNode, eventType) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent(eventType, true, true);
targetNode.dispatchEvent(clickEvent);
}
["mouseover", "mousedown", "mouseup", "click"].forEach(function(eventType) {
triggerMouseEvent(targetNode, eventType);
});
}
调用示例:
simulateMouseClick(document);
simulateMouseClick(document.querySelector("a[href*='stackoverflow']"));
位优化
function fireMouseEvents( query, eventNames ){
var element = document.querySelector(query);
if(element && eventNames && eventNames.length){
for(var index in eventNames){
var eventName = eventNames[index];
if(element.fireEvent ){
element.fireEvent( 'on' + eventName );
} else {
var eventObject = document.createEvent( 'MouseEvents' );
eventObject.initEvent( eventName, true, false );
element.dispatchEvent(eventObject);
}
}
}
}
你会像这样开火
fireMouseEvents("a[href*='stackoverflow']",['mouseover','mousedown','mouseup','click']);