我知道这种document.form.button.click()方法。但是,我想知道如何模拟onclick事件。
document.form.button.click()
onclick
我在堆栈溢出的某个地方找到了此代码,但我不知道如何使用它:(
function contextMenuClick() { var element= 'button' var evt = element.ownerDocument.createEvent('MouseEvents'); evt.initMouseEvent('contextmenu', true, true, element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 1, null); element.dispatchEvent(evt); }
如何使用JavaScript触发鼠标单击事件?
(修改后的版本使之无需prototype.js即可工作)
function simulate(element, eventName) { var options = extend(defaultOptions, arguments[2] || {}); var oEvent, eventType = null; for (var name in eventMatchers) { if (eventMatchers[name].test(eventName)) { eventType = name; break; } } if (!eventType) throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported'); if (document.createEvent) { oEvent = document.createEvent(eventType); if (eventType == 'HTMLEvents') { oEvent.initEvent(eventName, options.bubbles, options.cancelable); } else { oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView, options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element); } element.dispatchEvent(oEvent); } else { options.clientX = options.pointerX; options.clientY = options.pointerY; var evt = document.createEventObject(); oEvent = extend(evt, options); element.fireEvent('on' + eventName, oEvent); } return element; } function extend(destination, source) { for (var property in source) destination[property] = source[property]; return destination; } var eventMatchers = { 'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/, 'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/ } var defaultOptions = { pointerX: 0, pointerY: 0, button: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, bubbles: true, cancelable: true }
您可以像这样使用它:
simulate(document.getElementById("btn"), "click");
请注意,作为第三个参数,您可以传入’options’。您未指定的选项取自defaultOptions(请参见脚本底部)。因此,例如,如果您想指定鼠标坐标,则可以执行以下操作:
simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 })
您可以使用类似的方法来覆盖其他默认选项。