MouseEvent.initMouseEvent()

已弃用: 不再推荐使用该特性。虽然一些浏览器仍然支持它,但也许已从相关的 web 标准中移除,也许正准备移除或出于兼容性而保留。请尽量不要使用该特性,并更新现有的代码;参见本页面底部的兼容性表格以指导你作出决定。请注意,该特性随时可能无法正常工作。

MouseEvent.initMouseEvent() 方法用以在鼠标事件创建时 (一般用 Document.createEvent()方法创建) 初始化其属性的值。

事件初始化是在事件被Document.createEvent()方法创建后必需的。这个方法必须在事件被EventTarget.dispatchEvent()方法发送出来前调用。一旦事件被发送后,它将不再起任何作用。

备注: 不要再用此方法,已过时。

使用特定的事件构造器来替代它,像 MouseEvent()创建并发送事件 页面里有更多的使用信息。

语法

js
initMouseEvent(type, canBubble, cancelable, view,
                     detail, screenX, screenY, clientX, clientY,
                     ctrlKey, altKey, shiftKey, metaKey,
                     button, relatedTarget)

参数

type

设置事件类型type 的字符串,包含以下几种鼠标事件:clickmousedownmouseupmouseovermousemovemouseout

canBubble

是否可以冒泡。取值集合见Event.bubbles

cancelable

是否可以阻止事件默认行为。取值集合见Event.cancelable

view

事件的 AbstractView 对象引用,这里其实指向window 对象。取值集合见 UIEvent.view

detail

事件的鼠标点击数量。取值集合见Event.detail

screenX

事件的屏幕的 x 坐标。取值集合见MouseEvent.screenX

screenY

事件的屏幕的 y 坐标。取值集合见MouseEvent.screenY

clientX

事件的客户端 x 坐标。取值集合见MouseEvent.clientX

clientY

事件的客户端 y 坐标。取值集合见MouseEvent.clientY

ctrlKey

事件发生时

control

键是否被按下。取值集合见MouseEvent.ctrlKey

altKey

事件发生时

alt

键是否被按下。取值集合见MouseEvent.altKey

shiftKey

事件发生时

shift

键是否被按下。取值集合见MouseEvent.shiftKey

metaKey

事件发生时

meta

键是否被按下。取值集合见MouseEvent.metaKey

button

鼠标按键值 button

relatedTarget

事件的相关对象。只在某些事件类型有用 (例如 mouseover ?和 mouseout)。其他的传 null。

示例

HTML

html
<div style="background:red;width:180px;padding:10px;">
  <div id="out"></div>
  <input type="text" />
</div>

JavaScript

js
document.body.onclick = function () {
  e = arguments[0];
  var dt = e.target,
    stag = dt.tagName.toLowerCase();
  document.getElementById("out").innerHTML = stag;
};
var simulateClick = function () {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent(
    "click",
    true,
    true,
    window,
    0,
    0,
    0,
    80,
    20,
    false,
    false,
    false,
    false,
    0,
    null,
  );
  document.body.dispatchEvent(evt);
};
simulateClick(); //Why it can not show "input" ?

这里有个在线演示

规范

此特性不属于任何规范,也不再有望成为标准。

请使用 MouseEvent() 构造函数代替。

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
initMouseEvent
Deprecated

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Deprecated. Not for use in new websites.

参阅