美文网首页
dom 事件绑定

dom 事件绑定

作者: 一爷之秋 | 来源:发表于2019-09-29 11:16 被阅读0次

    dom绑定事件有两种方法:

    • onclick
      onclick绑定事件,分为两种方法,一种是行内绑定,一种是动态绑定
      行内绑定:
      行内绑定,事件中的this指向window
    <!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>Document</title>
      <script>
        function display() {
          // this.style.background = 'yellow';
          console.log(this);
        }
      </script>
      <style>
        #test, #box {
          height: 300px;
          width: 300px;
        }
      </style>
    </head>
    <body>
      <div id="test" onclick="display()"></div>
    </body>
    </html>
    

    动态绑定:

    <!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>Document</title>
      <script>
         window.onload = function() {
           document.getElementById('box').onclick = function() {
             this.style.width = '500px';
           }
         }
      </script>
      <style>
        #test, #box {
          height: 300px;
          width: 300px;
        }
      </style>
    </head>
    <body>
      <div id="box"></div>
    </body>
    </html>
    
    • 添加事件监听
    <!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>Document</title>
      <script>
         window.onload = function() {
           // 事件监听的方法,添加的事件,可以重复多次添加同一事件,并同时生效
           document.getElementById('box').addEventListener('click', function() {
            this.style.background = 'yellow';
          });
          document.getElementById('box').addEventListener('click', function () {
            this.style.width = '500px';
          });
         }
      </script>
      <style>
        #test, #box {
          height: 300px;
          width: 300px;
        }
      </style>
    </head>
    <body>
      <div id="box"></div>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:dom 事件绑定

          本文链接:https://www.haomeiwen.com/subject/vncfpctx.html