js 原生方法 – 模拟浏览器的 点击事件
1. 创建自定事件并监听
可看看 MDN 的 Evnet, CustomEvent 对象
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>simulate click</title> </head> <body> <input type="button" value="clickMe" id="demo_click"> <script> const btn = document.getElementById('demo_click'); btn.onclick = function () { // alert('click complete!'); }; // 1. 创建自定义事件 const event = new Event('build'); // 自定义事件 document.addEventListener('build', function (e) { console.log('dispatch'); }, false); // dom 监听事件 document.dispatchEvent(event); // dom触发事件 </script> </body> </html>
模拟 浏览器的鼠标点击事件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>simulate click</title> </head> <body> <input type="button" value="clickMe" id="demo_click"> <script> const btn = document.getElementById('demo_click'); btn.onclick = function () { // alert('click complete!'); }; simulateClick(); // 2. 模拟 浏览器的鼠标点击事件 // 2.1 可以触发 onclick 事件(先触发) // 2.2 可以触发 addEventListener 事件(后触发) // 2.3 jQuery 的事件绑定底层就是 addEventListener , function simulateClick() { // 模拟 浏览器的鼠标点击事件 const event = new MouseEvent('click', { view: window, bubbles: true, cancelable: true }); btn.dispatchEvent(event); } </script> </body> </html>
最后
以上就是甜蜜咖啡豆最近收集整理的关于js 原生方法 -- 模拟浏览器的 点击事件js 原生方法 – 模拟浏览器的 点击事件的全部内容,更多相关js内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复