js 模拟鼠标事件

时间:2023-03-10 06:12:58
js 模拟鼠标事件
<!DOCTYPE html>
<html>
<head lang="zh-CN">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title></title>
<style>
.button {
width: 200px;
height: 200px;
background-color: antiquewhite;
margin: 20px;
text-align: center;
line-height: 200px;
}
</style>
</head>
<body>
<div class="button">Button</div>
<script>
"use strict";
var btn = document.querySelector('.button');
btn.addEventListener('click', function (event) {
console.log('OH~!You clicked me~!');
}, false);
var ev = new MouseEvent('click', {
cancelable: true,
bubble: true,
view: window
});
btn.dispatchEvent(ev);
</script>
</body>
</html>