JavaScript基础(14_事件)

事件

事件

  • 就是用户和浏览器之间的交互行为

  • 比如:点击按钮、鼠标移动、关闭窗口等等。。。

事件冒泡

  • 案例

  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>
        <style>
          #box1{
            width: 200px;
            height: 200px;
            background-color: yellowgreen;
          }
          #s1{
            background-color: yellow;
          }
        </style>
        <script type="text/javascript">
          window.onload = function () {
            /*
            事件的冒泡(Bubble)
              - 所谓的冒泡指的是事件的向上传导,当后代元素被触发时,其祖先元素相同的事件同时也会触发
              - 大部分冒泡是有用的,如果不希望发生事件冒泡,可以通过事件对象取消冒泡
            */
            // 为s1绑定一个单击响应函数
            var s1 =  document.getElementById("s1");
    ​
            s1.onclick = function(event){
              event = event || window.event;
              alert("我是span单击响应函数");
    ​
              // 取消冒泡
              event.cancelBubble = true;
            };
    ​
            // 为box1绑定一个单击响应函数
            var box1 =  document.getElementById("box1");
    ​
            box1.onclick = function(){
              alert("我是box1单击响应函数");
            };
    ​
            // 为body绑定一个单击响应函数
            document.body.onclick = function(){
              alert("我是body单击响应函数");
            };
          };
        </script>
      </head>
      <body>
        <div id="box1">
          我是box1
          <span id="s1">我是span</span>
        </div></body>
    </html>
    View Code 

事件委派

  • 案例 

  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>
        <style>
        </style>
        <script type="text/javascript">
          window.onload = function () {
            var u1 = document.getElementById("u1");
            // 点击按钮以后添加超链接
            var btn01 = document.getElementById("btn01");
            btn01.onclick = function(){
              var li = document.createElement("li");
              li.innerHTML = "<a href='javascript:;' class='link'>新建超链接</a>"
              u1.appendChild(li);
            };
    ​
            /*
            为每一个超链接绑定单击响应函数
            我们为每一个超链接都绑定了一个单机响应函数,这种操作比较麻烦
              而且这些操作只能为已有的超链接设置事件,而新添加的超链接必须得重新绑定
    ​
            事件的委派
              - 指将事件统一绑定给元素的共同祖先元素,这样当后代元素上的时间触发时,会一直冒泡到祖先元素
                从而通过祖先元素的响应函数来处理事件
              - 事件委派是利用了冒泡,通过委派可以减少事件绑定的次数,提高性能
            */
            var allA = document.getElementsByTagName("a");
            // 我们希望只绑定一次事件,即可应用到多个元素上,即使元素是后来添加的
            // 可以尝试将其绑定给元素的共同祖先元素
            // 为ul绑定单击响应函数
            u1.onclick = function(event){
    ​
              event = event  || window.event;
              // alert(this);
    // event中的target表示触发事件的对象
              // alert(event.target);
    if(event.target.className == "link"){
                // 如果触发事件的对象是我们期望的元素则执行,否则不执行
                alert("我是ul的单击响应函数");
              };
            };
          };
        </script>
      </head>
      <body>
        <button id="btn01">添加超链接</button>
        <ul id="u1" style="">
          <p>我是p元素</p>
          <li><a href="javascript:;" class="link">超链接1</a></li>
          <li><a href="javascript:;" class="link">超链接2</a></li>
          <li><a href="javascript:;" class="link">超链接3</a></li>
        </ul>
      </body>
    </html>
    View Code 

事件绑定

  • 案例

  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>
        <script type="text/javascript">
          window.onload = function () {
            // 为btn01绑定第二个响应函数时,会导致第一个绑定事件函数会失效
            // 使用 对象.事件 = 函数形式绑定的响应函数,只能同时为一个元素的一个事件绑定一个响应函数。
            // 如果绑定了多个,后面的函数会覆盖前面的 
            /*
            第二种绑定事件的方法
              addEventListerner()
                -  通过这个方法也可以 为元素绑定响应函数
                - 参数:
                  1 事件的字符串,不要on,比如onclick 写成click
                  2 回调函数,当事件触发时该函数会被调用function(){}
                  3 是否 在捕获阶段触发事件,需要一个布尔值,一般都传false
                - 可以为一个元素的相同事件同时绑定多个函数,事件被触发时,所有的响应函数会按照
                  函数绑定顺序依次触发
                - 不支持ie8 及一下浏览器
                  ie8中,可以使用 attachEvent()来绑定事件
                  参数
                    1 事件的字符串,要on
                    2  回调函数
                  这个方法也可以同时为一个事件绑定多个处理函数
                  执行顺序是后绑定先执行
            */
    ​
    ​
            // btn01.addEventListener("click",function(){
            //  alert("121212");
            // },false);
    /*
            定义一个函数,为了兼容ie8和其他浏览器
            addEventListener()中的this 是绑定事件的对象
            attachEvent()中的this,是window
            参数
              1 obj 要绑定事件的对象
              2 eventstr 事件的字符串(不要on)
              3  callback 回调函数
              4 兼容所有浏览器
            */
            function bind(obj, eventStr, callback){
              if(obj.addEventListener){
                // 大部分浏览器 
                obj.addEventListener(eventStr,  callback, false);
              }else{
                // ie8及以下浏览器
                obj.attachEvent("on"+eventStr, function(){
                  // 处理this=btn01(obj)
                  callback.call(obj);
                });
              };
            };
    ​
            bind(btn01, "click", function(){
              alert(11);
            });
            bind(btn01, "click", function(){
              alert(22);
            });
          };
        </script>
      </head>
      <body>
        <button id="btn01">点我一下</button>
      </body>
     
     
    </html>
    View Code

事件的传播

  • 案例

  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>
        <style>
          #box1{
            width: 300px;
            height: 300px;
            background-color: yellowgreen;
          }
    ​
          #box2{
            width: 200px;
            height: 200px;
            background-color: yellow;
          }
    ​
          #box3{
            width: 150px;
            height: 150px;
            background-color: skyblue;
          }
        </style>
        <script type="text/javascript">
          window.onload = function () {
            /*
            分别为3个div绑定单击响应函数
            */
            var box1 = document.getElementById("box1");
            var box2 = document.getElementById("box2");
            var box3 = document.getElementById("box3");
            /*
            事件的传播
              - 关于事件的传播网景公司和微软公司有不同那个的理解
              - 微软认为事件应该由内向外传播,当事件触发时,应该先触发当前元素上的事件,然后逐渐从内向外传播,依照冒泡
              - 网景公司认为事件应该由外向内传播,也就是与微软认为的截然相反(捕获阶段)
              - w3c综合了两个公司的方案,将事件的传播分成了三个阶段
                1 捕获阶段
                  - 在捕获阶段时,由外向内 向目标元素进行事件捕获,默认此时不会触发事件
                2 目标阶段
                  - 事件捕获到目标元素,捕获结束,并开始在目标元素上触发事件
                3 冒泡阶段
                  - 事件从目标元素向祖先元素传递,依次触发祖先元素上的事件。
    ​
                - 如果希望在捕获阶段触发事件,可以将addEventListener(,,true)
                  一般情况不会希望在捕获阶段触发事件,参数一般都填false
            */
    ​
            bind(box1, "click",function(){
              alert("我是box1的响应函数");
            });
            bind(box2, "click",function(){
              alert("我是box2的响应函数");
            });
            bind(box3, "click",function(){
              alert("我是box3的响应函数");
            });
          };
    ​
          function bind(obj, eventStr, callback){
              if(obj.addEventListener){
                // 大部分浏览器 
                obj.addEventListener(eventStr,  callback, false);
              }else{
                // ie8及以下浏览器
                obj.attachEvent("on"+eventStr, function(){
                  // 处理this=btn01(obj)
                  callback.call(obj);
                });
              };
            };
        </script>
      </head>
      <body>
        <div id="box1">
          <div id="box2">
            <div id="box3"></div>
          </div>
        </div>
      </body>
    </html>
    View Code

拖拽

  • 基础版

    • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
      <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <title>Untitled Document</title>
          <style>
            #box1{
              width: 100px;
              height: 100px;
              background-color: red;
              position: absolute;
            }
      ​
            #box2{
              width: 100px;
              height: 100px;
              background-color: yellow;
              position: absolute;
      ​
              left: 200px;
              top: 200px;
            }</style>
          <script type="text/javascript">
            window.onload = function () {
              /*
              拖拽box1元素
                - 拖拽的流程
                1 当鼠标在被拖拽的元素上按下时,开始拖拽     【onmousedown】
                2 当鼠标移动时,被拖拽的元素跟随鼠标移动   【onmousemove】
                3 当鼠标松开时,被拖拽元素被固定在当前位置    【onmouseup】
              */var box1 = document.getElementById("box1");
              // 绑定鼠标按下事件
              box1.onmousedown = function(event){
                // alert("鼠标按下咯!");
                // div的水平方向偏移量 = 鼠标.clientX - 元素.offsetLeft
                // div的垂直方向偏移量 = 鼠标.clientY - 元素.offsetTop
                event  =  event || window.event;
      ​
                var offset_x = event.clientX - box1.offsetLeft;
                var offset_y = event.clientY - box1.offsetTop;
      ​
      ​
                // 为document绑定Onmousemove事件
                document.onmousemove = function(event){
                  // 当鼠标移动时被拖拽元素跟随鼠标移动onmousemove
                  event = event || window.event;
      ​
                  var x = event.clientX - offset_x;
                  var y = event.clientY - offset_y;
      ​
                  // 修改box1的位置
                  box1.style.left = x + "px";
                  box1.style.top = y + "px";
                };
      ​
                // 绑定鼠标松开事件
                document.onmouseup = function(){
                  // 当鼠标松开时,被拖拽元素固定在当前位置
                  // 取消document的onmousemove事件
                  document.onmousemove = null;
                  // alert("松开了呀")
                  // 取消document的onmouseup事件
                  document.onmouseup = null;
                };
              }
            };
          </script>
        </head>
        <body>
          <div id="box1"></div><div id="box2"></div>
        </body>
      </html>
      View Code
  • 优化版

    • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
      <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <title>Untitled Document</title>
          <style>
            #box1{
              width: 100px;
              height: 100px;
              background-color: red;
              position: absolute;
            }
      ​
            #box2{
              width: 100px;
              height: 100px;
              background-color: yellow;
              position: absolute;
      ​
              left: 200px;
              top: 200px;
            }</style>
          <script type="text/javascript">
            window.onload = function () {
              /*
              拖拽box1元素
                - 拖拽的流程
                1 当鼠标在被拖拽的元素上按下时,开始拖拽     【onmousedown】
                2 当鼠标移动时,被拖拽的元素跟随鼠标移动   【onmousemove】
                3 当鼠标松开时,被拖拽元素被固定在当前位置    【onmouseup】
              */var box1 = document.getElementById("box1");
              // 绑定鼠标按下事件
              box1.onmousedown = function(event){
                // alert("鼠标按下咯!");
      // 设置box1捕获所有鼠标按下的事件(为了兼容IE8)
                // setCapture只有IE支持,如果用chrome调用时,会报错
      ​
                box1.setCapture && box1.setCapture();
      ​
                // div的水平方向偏移量 = 鼠标.clientX - 元素.offsetLeft
                // div的垂直方向偏移量 = 鼠标.clientY - 元素.offsetTop
                event  =  event || window.event;
      ​
                var offset_x = event.clientX - box1.offsetLeft;
                var offset_y = event.clientY - box1.offsetTop;
      ​
      ​
                // 为document绑定Onmousemove事件
                document.onmousemove = function(event){
                  // 当鼠标移动时被拖拽元素跟随鼠标移动onmousemove
                  event = event || window.event;
      ​
                  var x = event.clientX - offset_x;
                  var y = event.clientY - offset_y;
      ​
                  // 修改box1的位置
                  box1.style.left = x + "px";
                  box1.style.top = y + "px";
                };
      ​
                // 绑定鼠标松开事件
                document.onmouseup = function(){
                  // 当鼠标松开时,被拖拽元素固定在当前位置
                  // 取消document的onmousemove事件
                  document.onmousemove = null;
                  // alert("松开了呀")
                  // 取消document的onmouseup事件
                  document.onmouseup = null;
      ​
                  // 当鼠标松开,取消对setCapture()的捕获行为
                  box1.releaseCapture && box1.releaseCapture();
                };
      ​
                /*
                当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容
                  此时会导致拖拽功能出现异常,这个是我们浏览器提供的默认行为
                  如果不希望发生这个默认行为,则可以 通过return false来取消
                  但是对IE8不起作用
                */
                return false;
      ​
              };
            };
          </script>
        </head>
        <body>
          <p>我是一段文字</p>
          <div id="box1"></div><div id="box2"></div>
        </body>
      </html>
      View Code
  • 高级版

    • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
      <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <title>Untitled Document</title>
          <style>
            #box1{
              width: 100px;
              height: 100px;
              background-color: red;
              position: absolute;
            }
      ​
            #box2{
              width: 100px;
              height: 100px;
              background-color: yellow;
              position: absolute;
      ​
              left: 200px;
              top: 200px;
            }</style>
          <script type="text/javascript">
            window.onload = function () {
              /*
              拖拽box1元素
                - 拖拽的流程
                1 当鼠标在被拖拽的元素上按下时,开始拖拽     【onmousedown】
                2 当鼠标移动时,被拖拽的元素跟随鼠标移动     【onmousemove】
                3 当鼠标松开时,被拖拽元素被固定在当前位置   【onmouseup】
              */
              var box1 = document.getElementById("box1");
              var box2 = document.getElementById("box2");
              drag(box1);
              drag(box2);
      ​
              // 提取一个专门用来设置拖拽的函数
              // 参数1:开启拖拽的元素obj
              function drag(obj){
                obj.onmousedown = function(event){
      ​
                  // 设置box1捕获所有鼠标按下的事件(为了兼容IE8)
                  // setCapture只有IE支持,如果用chrome调用时,会报错
      ​
                  obj.setCapture && obj.setCapture();
      ​
                  event  =  event || window.event;
      ​
                  var offset_x = event.clientX - obj.offsetLeft;
                  var offset_y = event.clientY - obj.offsetTop;
      ​
                  document.onmousemove = function(event){
                    event = event || window.event;
      ​
                    var x = event.clientX - offset_x;
                    var y = event.clientY - offset_y;
      ​
                    obj.style.left = x + "px";
                    obj.style.top = y + "px";
                  };
      ​
                  document.onmouseup = function(){
                    document.onmousemove = null;
                    document.onmouseup = null;
      ​
                    obj.releaseCapture && obj.releaseCapture();
                  };
                  return false;
                };
              };
            };
          </script>
        </head>
        <body>
          <p>我是一段文字</p>
          <div id="box1"></div>
          <div id="box2"></div>
        </body>
      </html>
      View Code

       

滚轮事件

  • 案例

  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>
        <style>
          #box1{
            width: 100px;
            height: 100px;
            background-color: red;
          }
        </style>
        <script type="text/javascript">
          window.onload = function () {
            /*
            当鼠标滚轮向下滚动时,box1变长
            当鼠标滚轮向上滚动时,box1变短
    ​
            */var box1 = document.getElementById("box1");
            // 在火狐中不支持该属性
            // 如果要在火狐中使用滚轮事件,则需要通过addEventtListener()函数来绑定DOMMouseScroll事件
            box1.onmousewheel = function(event){
              // alert("滚了");
    ​
              event = event || window.event;
    ​
              // 判断鼠标滚轮滚动方向
              // 向上滚120,向下滚-120
              // wheelDelta不看大小,只看正负
              // alert(event.wheelDelta);
    if(event.wheelDelta > 0){
                box1.style.height = box1.clientHeight - 10 + "px";
              }else{
                box1.style.height = box1.clientHeight + 10 + "px";
              };
    ​
              // 当滚轮滚动时,如果浏览器有滚动条,滚动条会随之一起滚动
              // 这是浏览器默认行为,取消可以使用 return false
              return false
            };
          };
        </script>
      </head>
      <body style="height: 2000px;">
        <div id="box1"></div></body>
    </html>
    View Code 

键盘事件

  • 案例

  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>
        <style>
          #box1{
            width: 100px;
            height: 100px;
            background-color: red;}
    ​
    ​
        </style>
        <script type="text/javascript">
          window.onload = function () {
            /*
            键盘事件:
              1 onkeydown
                - 按键被按下
                - 对于onkeydown来说,如果一直按着某一个键不松手,事件则会连续触发
                - 当onkeydown连续触发时,第一次和第二次之间会间隔稍微长一些,其他的会非常快
                  这种设置是为了防止误操作发生
              2 onkeyup
                按键被松开
              键盘事件一般都会绑定给一些可以获取到焦点的对象或者是document
            */
            var input = document.getElementsByTagName("input")[0];
            input.onkeydown = function(event){
              event = event || window.event;
              // console.log("按了")
    // 数字的keycode=48-57
              if(event.keyCode >= 48 && event.keyCode <=57){
                // 在input框中输入内容,属于onkeydown的默认行为
                // 如果return false取消默认行为后,则输入的内容再文本框中不会出现文本内容了。
                return false;
              };
            }
          };
        </script>
      </head>
      <body>
     
        <input type="text"></body>
    </html>
    View Code
posted @ 2020-09-20 19:42  名叫蛐蛐的喵  阅读(140)  评论(0编辑  收藏  举报