js 事件方法

一、 常见事件

事件此事件发生在何时...
onabort图像的加载被中断。
onblur元素失去焦点。
onchange内容被改变时触发的事件。
onclick当用户点击某个对象时调用的事件句柄。
ondblclick当用户双击某个对象时调用的事件句柄。
onerror在加载文档或图像时发生错误。
onfocus元素获得焦点。
onkeydown某个键盘按键被按下。
onkeypress某个键盘按键被按下并松开。
onkeyup某个键盘按键被松开。
onload一张页面或一幅图像完成加载。
onmousedown鼠标按钮被按下。
onmousemove鼠标被移动。
onmouseout鼠标从某元素移开。
onmouseover鼠标移到某元素之上。
onmouseup鼠标按键被松开。
onreset重置按钮被点击。
onresize窗口或框架被重新调整大小。
onselect文本被选中。
onsubmit确认按钮被点击。
onunload用户退出页面。
scroll滚动条移动时触发事件

二、 常用属性

属性描述
clientX距离客户端(浏览器窗口)的偏移
pageX相对页面的偏移
screenX相对屏幕的偏移
offsetX相对容器的偏移
layerX正常文档流: 和 pageX 一致
定位: 和 offsetX 一致,相对该容器偏移
offsetLeft获取元素偏移
offsetTop获取元素偏移
offsetWidth获取元素宽度
offsetHeight获取元素高度
getBoundingClientRect()元素的绝对位置

三、 事件冒泡

事件流在结构中传递事件,按照监听事件的捕获冒泡模式触发

  • 事件捕获 从外到内
  • 事件冒泡 从内到外

解决方法

  1. 阻止事件流的传递 e.stopPropagation(e)

  2. 事件代理

<style>
  .top {
    width: 500px;
    height: 500px;
    background-color: skyblue;
  }

  .mid {
    width: 350px;
    height: 350px;
    background-color: pink;
  }

  .bot {
    width: 200px;
    height: 200px;
    background-color: orange;
  }
</style>

<body>
  <div class="top">
    <div class="mid">
      <div class="bot"></div>
    </div>
  </div>
  <script>
    var btn = document.querySelector("button");
    var ul = document.querySelector("ul");
    var i = 0;
    //子节点动态添加,也可以使用点击事件
    btn.addEventListener("click", function() {
      i++;
      ul.innerHTML += `<li>${i}</li>`;
    });
    ul.addEventListener("click", function(e) {
      if (e.target.tagName == "LI") {
        console.log(e.target.innerHTML);
      }
    });

    var div_top = document.querySelector(".top");
    var div_mid = document.querySelector(".mid");
    var div_bot = document.querySelector(".bot");

    // 解决方法 阻止事件流的传递 e.stopPropagation()
    div_top.addEventListener("click", function() {
      console.log("top");
    });
    div_mid.addEventListener("click", function(e) {
      e.stopPropagation(e); ////阻止事件流的传递 top的方法不会执行
      console.log("mid");
    });
    div_bot.addEventListener("click", function(e) {
      //点击bot 只做bot的事情
      //阻止事件流的传递
      // e.stopPropagation();
      console.log("bot", e);
    });
  </script>
</body>

四、 事件代理(委托)

原理: 利用事件流的特点,根据触发元素判断出用户行为,从而执行对应的事务, 节约事件监听的个数

event.target 返回触发事件的元素
event.currentTarget 返回绑定事件的元素

div_top.addEventListener("click", function(e) {
  //e.currentTarget  指的是监听元素本身(父级元素,top)
  //e.target         指的是触发的元素(点击的元素)

  if (e.target.className.indexOf("mid") >= 0) {
    console.log("mid");
    return;
  }
  if (e.target.className.indexOf("bot") >= 0) {
    console.log("bot");
    return;
  }
  console.log("top", e.target);
});

五、 事件监听 addEventListener()

<body>
  <!-- 1. 元素节点上添加属性 -->
  <!-- <button onclick="add()">点击</button> -->
  <button>点击</button>
  <input type="text" />
  <script>
    var btn = document.querySelector("button");
    // 2. 添加属性  和1.同理
    // btn.onclick = function () {
    // 	console.log(1);
    // }
    // btn.onclick = function () {
    // 	console.log(2);
    // }

    //监听事件是可以存在多个
    btn.addEventListener("click", myClick);
    //移除监听事件时,需要传事件名和具体的函数(函数名)

    window.addEventListener("load", function() {
      //外部资源加载完毕
    });
    window.addEventListener("load", function() {
      //某个dom操作
    });
    window.onload = function() {};
    // btn.addEventListener('click', function (e) { //事件对象
    // 	console.log(2)
    // });

    var inp = document.querySelector("input");
    inp.addEventListener("input", function(e) {
      // e.target === inp  相当于当前元素
      // this 在dom操作当中指的就是元素本身
      // console.log('input',e.target === inp, e.target === this, e.target.value)
    });
    inp.onkeydown = function() {};
    inp.addEventListener("keydown", function(e) {
      // console.log('keydown',this.value)
      console.log("keydown", e.keyCode);
      switch (e.keyCode) {
        case 87:
          console.log("上 w");
          break;
        case 83:
          console.log("下 s");
          break;
        case 65:
          console.log("左 a");
          break;
        case 68:
          console.log("右 d");
          break;
      }
    });
    inp.addEventListener("keyup", function(e) {
      // console.log('keyup', this.value)
    });

    inp.addEventListener("blur", function(e) {
      //失去焦点
      console.log("blur", this.value);
      if (this.value.indexOf("a") < 0) {
        this.style.borderColor = "red";
      } else {
        this.style.borderColor = "green";
      }
    });
    inp.addEventListener("focus", function(e) {
      this.style.borderColor = "blue";
    });

    var event = new Event("boom");
    console.log(event);

    btn.addEventListener("boom", function() {
      console.log("boom");
    });
    function myClick(e) {
      //事件对象
      console.log(1);
      btn.removeEventListener("click", myClick);
      //主动触发事件boom
      btn.dispatchEvent(event);
    }

    btn.addEventListener("mousedown", function() {
      console.log("鼠标摁下");
    });
    btn.addEventListener("mouseup", function() {
      console.log("鼠标松开");
    });
    btn.addEventListener("mouseenter", function() {
      console.log("鼠标移入");
    });
    btn.addEventListener("mouseleave", function() {
      console.log("鼠标移出");
    });

    //触点(移动端)
    document.addEventListener("touchstart", function() {
      console.log("touchstart");
    });
    document.addEventListener("touchmove", function(e) {
      console.log("touchmove", e);
    });
    document.addEventListener("touchend", function() {
      console.log("touchend");
    });
  </script>

六、 事件绑定

var btn = document.querySelector("button");
var btn = document.getElementsByTagName("button");
//btn的点击事件
//需要我们逐个设置
//onclick 如果重新设置,后者会替代前者
for (var i = 0; i < btn.length; i++) {
  btn[i].onclick = function() {
    alert("哈哈");
  };
}

function handleClick() {
  alert("haha");
}

//如果有多个listener,也不会互相覆盖,而是监听相同的事件,执行不同的回调
var div = document.querySelector("div");
div.addEventListener("click", text);
function text() {
  console.log("单击下,div的addEventListener");
}
div.addEventListener("click", function() {
  console.log("txet,div的addEventListener");
});
div.addEventListener("dblclick", function() {
  console.log("双击下,div的addEventListener");
});

//移除事件的监听,要找到具体对应的回调函数,所以回调函数最好有个具体的名字
div.removeEventListener("click", text);

div.addEventListener("touchstart", function(e) {
  console.log(e);
});

七、 拖拽

var box = document.querySelector(".box");

box.addEventListener("drag", function(e) {
  console.log(e.pageX);
  //		box.style.cursor="-webkit-grabbing";
});

box.addEventListener("dragend", function(e) {
  //				alert("end")
  box.style.left = e.pageX - box.offsetWidth / 2 + "px";
  box.style.top = e.pageY - box.offsetHeight / 2 + "px";
});

//touchstart        touchmove          touchend
//第一次的坐标       移动坐标            松手的坐标
//		box.addEventListener("touchstart",function(){
//			//拖拽开始   打开开关
//			box.flag = true
//		})
box.addEventListener("touchmove", function(e) {
  //				console.log(23)
  //手指的位置
  var handX = e.changedTouches[0].pageX;
  var handY = e.changedTouches[0].pageY;
  box.style.left = handX - box.offsetWidth / 2 + "px";
  box.style.top = handY - box.offsetHeight / 2 + "px";
});
//			box.addEventListener("touchend",function(){
//				//拖拽开始   打开开关
//				console.log("完成")
//			})
Last Updated:
Contributors: zerojs