1 回答
TA贡献1826条经验 获得超6个赞
您可以创建事件,当然也可以MouseEvents
自己创建。
在现代浏览器中,您可以通过调用所需事件类型的构造函数来完成此操作,或者通过调用document.createEvent('<EventName>')
https://developer.mozilla.org/en-US/docs/Web/API/Event
然后,您可以使用https://developer.mozilla.org/de/docs/Web/API/EventTarget/dispatchEvent在您喜欢的任何元素上触发此事件dispatchEvent()
document.getElementById("button").addEventListener('mousedown', mouseDown);
document.getElementById("button").addEventListener('mouseup', mouseUp);
function mouseDown() {
document.getElementById("button").innerHTML = "The mouse button is held down.";
}
function mouseUp() {
document.getElementById("button").innerHTML = "You released the mouse button.";
}
// bind click event on simulate button
document.querySelector('.simulate').addEventListener('click', () => {
console.log('start');
simulateMouseEvent(document.getElementById("button"), 'mousedown')
setTimeout(() => {
console.log('end');
simulateMouseEvent(document.getElementById("button"), 'mouseup')
}, 5000)
})
// capsulate the event trigger stuff
// see: http://youmightnotneedjquery.com/
function simulateMouseEvent(el, eventName){
let event;
if (window.MouseEvent && typeof window.MouseEvent === 'function') {
event = new MouseEvent(eventName);
} else {
event = document.createEvent('MouseEvent');
event.initMouseEvent(eventName);
}
el.dispatchEvent(event);
}
<!DOCTYPE html>
<html>
<body>
<p>
<button class="button" id="button">You released the mouse button.</button>
</p>
<p>
<button class="simulate">simulate</button>
</p>
</body>
</html>
添加回答
举报