我想模拟整个点击而不仅仅是
document.getElementsByClassName()[0].click();
我该怎么做?搜索结果似乎都是关于处理此类事件,而不是触发它们。
答案 0 :(得分:82)
发送鼠标事件。像这样:
//--- 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();
答案 1 :(得分:4)
比特优化
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']);
答案 2 :(得分:2)
在Brock's code达到预期效果后,我进行了改进。
定义:
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']"));