js原生创建模拟事件和自定义事件的方法

让我万万没想到的是,原来《JavaScript高级程序设计(第3版)》里面提到的方法已经是过时的了.后来我查看了MDN,才找到了最新的方法.

  1. 模拟鼠标事件
    MDN上已经说得很清楚,尽管为了保持向后兼容MouseEvent.initMouseEvent()仍然可用,但是呢,我们应该使用MouseEvent().
    我们使用如下页面做测试

    <!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>

    打开一下这个页面,并且在打开控制台的情况下,你就可以看到控制台打印了一句话,证明模拟成功了.
    如下图所示:

    Screenshot from 2015-05-19 12:20:40.png
    Screenshot from 2015-05-19 12:20:40.png

    当然,在构建这个MouseEvent对象的时候还是有很多属性可以填写的,不过,可能就是示例的那几个比较有用,如果像查看更多的属性,请查看如下地址
    (由于MouseEvent继承自UIEvent和Event,所以,他也继承了他们的属性)
    https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
    https://developer.mozilla.org/en-US/docs/Web/API/UIEvent
    https://developer.mozilla.org/en-US/docs/Web/API/Event
    想查看MouseEvent()构造器的具体用法,请查看
    https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent

  2. 模拟键盘事件
    打开控制台,并且重新载入页面,你就可以看到控制台打印了字母'A'

    <!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');
         document.addEventListener('keyup', function (event) {
             console.log(String.fromCharCode(event.keyCode));
         }, false);
         var ev = new KeyboardEvent('keyup', {
             keyCode: 65
         });
         document.dispatchEvent(ev);
     </script>
    </body>
    </html>

    如下是KeyBoardEvent的详细说明
    https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

  3. 自定义事件
    自定义事件有两种方法,一种是使用new Event(),另一种是new customEvent()

    1. new Event()

      <!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');
        var ev = new Event('test', {
            bubbles: 'true',
            cancelable: 'true'
        });
        btn.addEventListener('test', function (event) {
            console.log(event.bubbles);
            console.log(event.cancelable);
            console.log(event.detail);
        }, false);
        btn.dispatchEvent(ev);
      </script>
      </body>
      </html>

      运行效果如下所示,请先注意,event.detail的值为undefined

      Screenshot from 2015-05-19 12:37:01.png
      Screenshot from 2015-05-19 12:37:01.png
    2. new customEvent()

      <!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');
      
        var ev = new CustomEvent('test', {
            bubbles: 'true',
            cancelable: 'true',
            detail: 'tcstory'
        });
        btn.addEventListener('test', function (event) {
            console.log(event.bubbles);
            console.log(event.cancelable);
            console.log(event.detail);
        }, false);
        btn.dispatchEvent(ev);
      </script>
      </body>
      </html>

      效果如下图

      Screenshot from 2015-05-19 12:40:30.png
      Screenshot from 2015-05-19 12:40:30.png

      可以很明显的看到,其实new customEvent()比new Event()多了可以在event.detail属性里携带自定义数据的功能(event.detail的值为tcstory),这就是差别了.
      Event()的详细说明
      https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
      customEvent() 的详细说明
      https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent

总结下来发现,除了模拟自定义事件比较有用的话,模拟鼠标事件和键盘事件则好像有点坑和不一致性.以模拟键盘事件来说吧.
KeyboardEvent.key在MDN上的文档被提示为推荐使用的属性,而KeyboardEvent.keyCode却被说成是不推荐使用的,应该使用key属性,然而你去看KeyboardEvent.key的文档就会发现,这个属性压根就没得到多少浏览器的支持,如果用这个属性,简直就是掉坑里了.
下图所示,一大片的红字啊

Screenshot from 2015-05-19 12:48:15.png
Screenshot from 2015-05-19 12:48:15.png



文/中华田园犬(简书作者)
原文链接:http://www.jianshu.com/p/418e9e35d5a1
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
posted @ 2016-10-10 00:12  最骚的就是你  阅读(2317)  评论(0编辑  收藏  举报