事件流
事件冒泡
事件捕获
DOM事件流
DOM2 Events规定事件流分为三个阶段,事件捕获、到达目标和事件冒泡
HTML事件处理程序
示例
<input type="button" onclick="console.log('clicked')"/>
DOM0事件处理程序
事件处理程序
鼠标事件
鼠标和滚轮事件
click:点击鼠标左键触发
dbclick:双击鼠标左键触发
mousedown:鼠标按下任意键触发
mouseenter:鼠标光标移入元素内部触发
mouseleave:鼠标光标移出元素内部触发
mousemove:鼠标光标移动触发
mouseout:鼠标光标从一个元素内部移入到另一个元素内部时触发
mouseover:鼠标光标从元素外部移动到元素内部时触发
mouseup:用户释放鼠标时触发
mousewheel:鼠标滚轴事件
示例
window.addEventListener("click",function(event){...})
示例:滑块练习
<style>
body {overflow: hidden;}
#div {
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 200px;
top: 200px;
}
</style>
<body><div id="div"></div></body>
<script type="text/javascript">
window.onload = function () {
var oDiv = document.getElementById('div');
oDiv.onmousedown = function (ev) {
var ev = ev || event;
var oLeft = ev.clientX - this.offsetLeft;
var oTop = ev.clientY - this.offsetTop;
function myfunction(ev) {
var ev = ev || event;
oDiv.style.left = ev.clientX - oLeft + 'px';
oDiv.style.top = ev.clientY - oTop + 'px';
console.log(ev.clientX);
}
window.addEventListener("mousemove", myfunction)
function re(){
window.removeEventListener("mousemove",myfunction)
window.removeEventListener("mouseup",re)
}
window.addEventListener("mouseup",re)
}
}
</script>
客户端坐标、页面坐标和屏幕坐标
客户端(视口)坐标:event对象的clientX,clientY
页面坐标:event对象的pageX,pageY
屏幕坐标:event对象的screenX,screenY
键盘事件
DOM2 Events包含了3个事件
keydown:
keyup:
keypress:
DOM3 Events 废弃了keypress ,推荐使用textInput
textInput:
其字符被输入到可编辑区域时触发
示例:
<script type="text/javascript">
var div = document.createElement("div");
document.body.appendChild(div);
div.style.width = "100px";
div.style.height = "100px";
div.style.backgroundColor = "red";
div.style.position = "absolute";
div.style.top = "0";
div.style.left = "0";
document.onkeydown = function(e) {
var speed = 10;
switch(e.which){
case 38:
div.style.top = parseInt(div.style.top) - speed + "px";
break;
case 40:
div.style.top = parseInt(div.style.top) + speed + "px";
break;
case 37:
div.style.left = parseInt(div.style.left) - speed + "px";
break;
case 39:
div.style.left = parseInt(div.style.left) + speed + "px";
break;
}
}
</script>
事件委托
事件委托
过多事件处理程序的解决方案是使用事件委托
事件委托利用事件冒泡,可以使用一个事件处理程序来管理一种类型的事件
<ul id="myLinks">
<li id="goSomewhere">Go goSomewhere</li>
<li id="doSomething">Do doSomething</li>
<li id="sayhi">Say hi</li>
</ul>
<script type="text/javascript">
(function(){
let list = document.getElementById("myLinks")
list.addEventListener("click",(e)=>{
let target = e.target
switch(target.id){
case("goSomewhere"):
document.title = "I changed the document`s title";
break;
case("doSomething"):
location.href= "https://www.baidu.com"
break;
case("sayhi"):
console.log("sayhi");
break;
}
})
})()
</script>
模拟事件