问题描述
我知道 document.form.button.click()
方法。但是,我想知道如何模拟onclick事件。
I know about the document.form.button.click()
method. However, I'd like to know how to simulate the onclick event.
我在Stack Overflow上找到了这个代码,但我不知道如何使用它:(
I found this code somewhere here on Stack Overflow, but I don't know how to use it :(
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触发鼠标单击事件?
How do I fire a mouse click event using JavaScript?
推荐答案
(修改后的版本使其无需prototype.js)
(Modified version to make it work without 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");
请注意,作为第三个参数,您可以传递选项。您未指定的选项取自defaultOptions(请参阅脚本底部)。因此,如果您想要指定鼠标坐标,您可以执行以下操作:
Note that as a third parameter you can pass in 'options'. The options you don't specify are taken from the defaultOptions (see bottom of the script). So if you for example want to specify mouse coordinates you can do something like:
simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 })
你可以使用类似的方法覆盖其他默认选项。
You can use a similar approach to override other default options.
积分应转到。 是原始来源(prototype.js特定)。
Credits should go to kangax. Here's the original source (prototype.js specific).
这篇关于如何使用JavaScript模拟鼠标点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!