JavaScript 事件和事件类型
事件和事件类型
认识事件和事件类型
什么是事件
事件是发生并得到处理的操作,即:事情来了,然后处理。
如:
电话铃声响起(事件发生) ——需要接电话(处理)
按钮被点击了,然后对应一个函数来处理
事件绑定
1、内联模式
2、外联模式/脚本模式(使用较多)
绑定事件格式:
元素节点.on + 事件类型 = 匿名函数
click 事件类型
onclick 事件处理的函数
<script>function btnClick(){alert("内联模式");}window.onload = function(){var oBtn = document.getElementById("btn1");oBtn.onclick = function(){alert("外联模式");}}</script>
</head>
<body><button onclick="btnClick();">内联模式</button><button id="btn1">外联模式</button>
</body>
事件类型的种类
- 鼠标事件(可以绑定在任意的元素节点上)
- click:单击
- dblclick:双击
- mouseover:鼠标移入 【注】经过子节点会重复触发
- mouseout:鼠标移出 【注】经过子节点会重复触发
- mousemove:鼠标移动(会不停地触发)
- mousedown: 鼠标按下
- mousup:鼠标抬起
- mouseenter:鼠标移入 【注】经过子节点不会重复触发 IE8以后才有
- mouseleave:鼠标移出 【注】经过子节点不会重复触发 IE8以后才有
<style>#div1{width: 200px; height: 200px; background-color: red;}</style><script>window.onload = function(){var oBtn = document.getElementById("btn1");oBtn.ondblclick = function(){alert("双击");}oBtn.onmouseover = function(){this.style.backgroundColor = 'red';}oBtn.onmouseout = function(){this.style.backgroundColor = 'blue';}oBtn.onmousedown = function(){this.innerHTML = "按下";}oBtn.onmouseup = function(){this.innerHTML = "抬起";}var oDiv = document.getElementById("div1");var i = 0;oDiv.onmousemove = function(){this.innerHTML = i++;}}</script><body><button id="btn1">按钮</button><div id="div1"></div>
</body>
mouseover与mouseenter
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div{width: 100px; height: 100px; background-color: gray; line-height: 100px; text-align: center; margin: 20px; padding: 50px;}div span{width: 100px; height: 100px; background-color: white; display: inline-block;}</style><script>window.onload = function(){var aDivs = document.getElementsByTagName("div");var i = 0;aDivs[0].onmouseover = function(){var oSpan = this.getElementsByTagName("span")[0];oSpan.innerHTML = i++;}var j = 0;aDivs[1].onmouseenter = function(){var oSpan = this.getElementsByTagName("span")[0];oSpan.innerHTML = j++;}}</script>
</head>
<body><div><span>mouseover</span></div><div><span>mouseenter</span></div>
</body>
</html>
mouseout与mouseleave
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div{width: 100px; height: 100px; background-color: gray; line-height: 100px; text-align: center; margin: 20px; padding: 50px;}div span{width: 100px; height: 100px; background-color: white; display: inline-block;}</style><script>window.onload = function(){var aDivs = document.getElementsByTagName("div");var i = 0;aDivs[0].onmouseout = function(){var oSpan = this.getElementsByTagName("span")[0];oSpan.innerHTML = i++;}var j = 0;aDivs[1].onmouseleave = function(){var oSpan = this.getElementsByTagName("span")[0];oSpan.innerHTML = j++;}}</script>
</head>
<body><div><span>mouseout</span></div><div><span>mouseleave</span></div>
</body>
</html>
- 键盘事件(表单元素,全局window)
keydown 键盘按下(如果按下不放手,会一直触发)
keyup 键盘抬起
keypress 键盘按下(只支持字符键)
window.onload = function(){var i = 0;// window.onkeydown = function(){// document.title = i++;// }window.onkeypress = function(){document.title = i++;//功能键不支持(shift、大小写切换等)}window.onkeyup = function(){document.title = '抬起';}}
Event事件类型(window和表单)
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div{padding: 50px;}#div1{background-color: red;}#div2{background-color: blue;}#div3{background-color: orange;}</style><script>/* 浏览器天生就会事件冒泡 */window.onload = function(){var aDivs = document.getElementsByTagName("div");for(var i = 0; i < aDivs.length; i++){aDivs[i].onclick = function(ev){var e = ev || window.event;alert(this.id);// e.cancelBubble =true;e.stopPropagation();}}}</script>
</head>
<body><div id="div1"><div id="div2"><div id="div3"></div></div></div>
</body>
</html>
/* 浏览器天生就会事件冒泡 */window.onload = function(){var aDivs = document.getElementsByTagName("div");for(var i = 0; i < aDivs.length; i++){aDivs[i].onclick = function(ev){var e = ev || window.event;alert(this.id);// e.cancelBubble =true;// e.stopPropagation();stopBubble(e);}}//封装跨浏览器兼容的阻止事件冒泡function stopBubble(e){//e是事件对象if(e.stopPropagation){e.stopPropagation();}else{e.cancelBubble = true;}}}
事件练习
跟随鼠标移动的动图
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>*{margin: 0px; padding: 0px;}#div1{width: 208px; height: 208px; background: url(WL54Z3SST0R[]S16VJ\({EQH.gif) no-repeat; position: absolute;}</style><script>window.onload = function(){var oDiv = document.getElementById("div1");document.onmousemove = function(ev){var e = ev || window.event;oDiv.style.left = e.clientX - 25 + 'px';oDiv.style.top = e.clientY - 25 + 'px';}}</script>
</head>
<body><div id="div1"></div>
</body>
</html>
跟随鼠标一串的效果
先把最后一个往前挪,再把倒数第二往前挪...依次这样才会有跟随效果;否则先挪第一个第二个会找不到原来第一个的位置
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>*{margin: 0px; padding: 0px;}div{position: absolute; width: 20px; height: 20px; background-color: red; border-radius: 50%;}</style><script>window.onload = function(){var arr = document.getElementsByTagName("div");document.onmousemove = function(ev){var e = ev || window.event;for(var i = arr.length - 1; i > 0; i--){arr[i].style.left = arr[i - 1].offsetLeft + "px";arr[i].style.top = arr[i - 1].offsetTop + "px";}//让下标0的div跟随鼠标移动arr[0].style.left = e.clientX + 'px';arr[0].style.top = e.clientY + 'px';}}</script>
</head>
<body><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</body>
</html>
阻止默认行为
隐藏系统默认菜单,自己写一个菜单且跟随鼠标移动
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>*{margin: 0px; padding: 0px;}#menu{width: 100px; height: 100px; background-color: gray; display: none; position: absolute;}</style><script>window.onload = function(){//官方的右键菜单document.oncontextmenu = function (){return false;//阻止了可运行菜单}/* 实现自定义的右键菜单,鼠标按下按下的使右键,在右键这个位置显示菜单如果按下的是别的键,菜单消失*/var oMenu = document.getElementById("menu");document.onmousedown = function(ev){var e = ev || window.event;if(e.button == 2){oMenu.style.display = 'block';oMenu.style.left = e.clientX + "px";oMenu.style.top = e.clientY + "px";}else{oMenu.style.display = 'none';}}}</script>
</head>
<body><div id="menu"><ul><li>菜单1</li><li>菜单2</li><li>菜单3</li></ul></div>
</body>
</html>
阻止超链接的默认行为:
1、简陋的阻止a链接默认行为的方式
缺点:运行到了return,后续的内容我们就运行不到了
2、规范的方法:
preventDefault(); W3C,阻止默认行为,放哪里都可以
window.event.returnValue = false;IE,阻止默认行为
!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script>/* //1、简陋的阻止a链接默认行为的方式window.onload = function(){var a1 = document.getElementById("a1");a1.onclick = function(){// return false;return confirm("你确认要离开当前页面吗?");}} *///2、规范的方法window.onload = function(){var a1 = document.getElementById("a1");a1.onclick = function(ev){var e = ev || window.event;preDef(e);alert("后续的操作");}}/* 编写一个跨浏览器阻止超链接默认行为的函数 */function preDef(e){if(e.preventDefaul){e.preventDefaul();}else{window.event.returnValue = false;}}</script>
</head>
<body><a id="a1" href="https://www.baidu.com">百度</a>
</body>
</html>
HTML事件
window事件
resize:窗口大小发生变化的时候都触发
<script>window.onload = function(){alert(2); //页面全部加载完毕之后再执行}</script><body><h1>hello world</h1>
</body>
<script>alert(1);
</script>
<script>window.onload = function(){var i = 0;window.onscroll = function(){document.title = i++;}}</script><body style="height: 3000px;"><h1>hello world</h1>
</body>
<script>window.onload = function(){var i = 0;window.onresize = function(){document.title = i++;}}</script><body style="height: 3000px;"><h1>hello world</h1>
</body>
scroll:页面滚动
unload:当前页面解构的时候触发(刷新页面,关闭当前页面)IE浏览器兼容
load:当前页面加载完成以后会触发
表单事件
reset:当我们点击reset上的按钮才能触发 【注】必须添加在form元素上
<script>window.onload = function(){var oInput1 = document.getElementById("input1");var oF1 = document.getElementById("f1");oF1.onsubmit = function(){alert("提交");}oF1.onreset = function(){alert("重置");}}</script><body style="height: 3000px;"><form id="f1"><input type="text"/><input type="submit"/><input type="reset"/></form>
</body>
submit:当我们点击submit上的按钮才能触发 【注】必须添加在form元素上
change:当我们对输入框的文本进行修改并且失去焦点的时候
<script>window.onload = function(){var oInput1 = document.getElementById("input1");oInput1.onchange = function(){alert("被修改了");//修改(增、删)文本后并且失去了焦点才触发}}</script><body style="height: 3000px;"><input value="默认文本" id="input1" type="text"/>
</body>
select:当我们在输入框内选中文本的时候触发
<script>window.onload = function(){var oInput1 = document.getElementById("input1");oInput1.onselect = function(){alert("被选中了");//选中文本的时候触发}}</script><body style="height: 3000px;"><input value="默认文本" id="input1" type="text"/>
</body>
focus:获取焦点(光标)
blur:失去焦点
<script>window.onload = function(){var oInput1 = document.getElementById("input1");oInput1.onblur = function(){this.value = "失去焦点";}oInput1.onfocus = function(){this.value = "获取焦点";}}</script><body style="height: 3000px;"><input value="默认文本" id="input1" type="text"/>
</body>
事件对象
事件绑定:元素节点.on + 事件类型 = 匿名函数;
【注】系统会在事件绑定一旦完成的时候,生成一个对象。
【注】触发事件的时候,系统会自动去调用事件绑定的函数,将事件对象当作第一个参数传入
<script>/* //普通函数:第一步封装函数,封装好函数后不会函数不会直接调用,只用通过函数名才可以将函数调用,函数才可执行function show(){alert("hello world");}show(); */ //点击按钮后,函数才会被调用;调用的代码不是由我们自己写的,是由系统写的//证明系统传参了var show = function (ev){/* //方法一:不需要形参就可以直接拿到alert(arguments.length);//1alert(arguments[0]);//[object PointerEvent] *///方法二:传入形参ev// alert(ev);//这种通过形参拿事件对象的方式在IE8以下不兼容。IE8以下使用 window.event;var e = ev || window.event;alert(e);//[object PointerEvent]alert("hello world");}window.onload = function(){var oBtn = document.getElementById("btn1");//oBtn.onclick = show;oBtn.onclick = function(ev){//事件对象获取方式(固定写法)var e = ev || Window.event;alert(e);}}</script><body><button id="btn1">按钮</button>
</body>
事件对象属性
button的属性
弹出 0 用左键按
弹出 1 用滚轮按
弹出 2 用右键按
<script>window.onload = function(){document.onmousedown = function(ev){var e = ev || window.event;alert(e.button);}}</script><body><button>按钮</button>
</body>
获取当前鼠标位置:(原点位置不一样)
clientX clientY 原点位置:可视窗口的左上角为原点
pageX pageY 原点位置:整个页面的左上角(包含滚出去的滚动距离)
screenX screenY 原点位置:电脑屏幕的左上角
<script>window.onload = function(){document.onmousedown = function(ev){var e = ev || window.event;// alert(e.button);alert(e.clientX + "," + e.clientY);// alert(e.pageX + "," + e.pageY);alert(e.screenX + "," + e.screenY);}}</script><body style="height: 3000px;"><h1>hello world</h1>
</body>
跟随鼠标提示框
事件类型:
mouseover:让提示框显示
mouseout:让提示框隐藏
mousemove:让提示框跟随鼠标移动
clienX clientY 原点位置:可视窗口的左上角为原点
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>a{display: block; font-size: 40px; margin: 100px; width: 130px;}#msg{width: 600px; height: 150px; background-color: gray; color: white; display: none; position: absolute;}</style><script>var arr = ["李世民(599年1月23日—649年7月10日),祖籍陇西成纪(今甘肃秦安),一说陇西狄道(今甘肃省临洮县)人,又说钜鹿郡人。唐朝第二位皇帝(626年—649年在位),政治家、战略家、军事家、书法家、诗人。","唐高宗李治(628年7月21日 [1-2] -683年12月27日 [3] ),字为善,唐朝第三位皇帝(649年7月15日-683年12月27日在位),唐太宗李世民第九子,母为文德顺圣皇后长孙氏,前太子李承乾、魏王李泰同母弟。","武曌[zhào] [1] (624年-705年12月16日 [2] ),即武则天,并州文水(今山西省文水县)人。唐朝至武周时期政治家,武周开国君主(690年-705年在位),也是中国历史上唯一的正统女皇帝、即位年龄最大(67岁)及寿命最长的皇帝之一(82岁)。","唐玄宗李隆基(685年9月8日—762年5月3日),唐高宗李治与武则天之孙,唐睿宗李旦第三子,故又称李三郎,母窦德妃。 [1] 唐朝在位最长的皇帝(712年—756年在位)。"];//【注】arr数组中是按照a标签的下标去存储对应的描述信息的window.onload = function(){var aAs = document.getElementsByTagName("a");var oMsg = document.getElementById("msg");for(var i = 0; i < aAs.length; i++){aAs[i].index = i;aAs[i].onmouseover = function(){oMsg.innerHTML = arr[this.index];oMsg.style.display = 'block';}aAs[i].onmouseout = function(){oMsg.style.display = 'none';}//添加鼠标移动事件aAs[i].onmousemove = function(ev){var e = ev|| window.event;oMsg.style.left = e.clientX + 5 + "px";oMsg.style.top = e.clientY + 5 + "px";}}}</script>
</head>
<body><a href="#">唐太宗</a><a href="#">唐高宗</a><a href="#">武则天</a><a href="#">唐玄宗</a><div id="msg"></div>
</body>
</html>
鼠标事件对象的属性
shiftKey:按下shift键,为true,默认为false
altKey:按下alt键,为true,默认为false
ctrlKey:按下ctrl键,为true,默认为false
metaKey:windows系统 windowsI(开始)键位true; macos系统 按下command键位true
【注】和别的操作进行组合,形成一些快捷键操作。
window.onload = function(){document.onmousedown = function(ev){var e = ev || window.event;var arr = [];if(e.shiftKey){arr.push("shift");}if(e.altKey){arr.push("alt");}if(e.ctrlKey){arr.push("ctrl");}if(e.metaKey){arr.push("windows");}alert(arr);}}
键盘事件对象的属性
keyCode:键码
which
返回值:键码返回的是大写字母的ASCII码值,不区分大小写。
格式:var which = e.which || e.keyCode;
【注】只在keydown下支持。
window.onload = function(){window.onkeydown = function(ev){var e = ev ||window.event;var which = e.which || w.keyCode;alert(which);}}
charCode 字符码
which
返回值:字符码区分大小写,返回当前按下键对应字符的ASCII码值
格式:var which = e.which || e.charCode;
【注】只在keypress下支持,只支持字符键
window.onload = function(){window.onkeypress = function(ev){var e = ev ||window.event;var which = e.which || w.charCode;alert(which);}}
事件冒泡和目标对象
target:目标对象/触发对象
【注】这个事件是由谁而起的
IE8以下不兼容 兼容的对应属性为window.event.srcElement;
<script> window.onload = function(){var oLi = document.getElementById("li1");// oLi.onclick = function(ev){// var e = ev || window.event;// var target = e.target || window.event.srcElement;// // alert(this.innerHTML);// alert(target.innerHTML);// }var oUl = document.getElementById("ul1");oUl.onclick = function(ev){var e = ev || window.event;var target = e.target || window.event.srcElement;alert(this.tagName);alert(target.innerHTML);}}</script><body><ul id="ul1"><li id="li1">1111</li><li>2222</li><li>3333</li></ul>
</body>
浏览器上事件天生的一个特点:事件流
事件冒泡:由里向外逐级触发
事件捕获:由外向里逐级触发
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div{padding: 50px;}#div1{background-color: red;}#div2{background-color: blue;}#div3{background-color: orange;}</style><script>/* 浏览器天生就会事件冒泡 */window.onload = function(){var aDivs = document.getElementsByTagName("div");for(var i = 0; i < aDivs.length; i++){aDivs[i].onclick = function(){alert(this.id);//点击红色的地方触发div1;点击蓝色的地方先触发div2再触发div1;点击橙色的地方先触发div3再触发div2最后出触发div1}}}</script>
</head>
<body><div id="div1"><div id="div2"><div id="div3"></div></div></div>
</body>
</html>
阻止事件冒泡:浏览器兼容问题
拿到事件对象的属性和方法
- cancelBubble
- stopPropagation
拖拽
(拖拽三剑客)
伪代码(代码草稿)
mousedown
鼠标按下时,记录鼠标按下位置和被拖拽物体的相对距离
var offsetX = e.clientX - node.offsetLeft;
var offsetY = e.clientY - node.offsetTop;
mousemove
一直保持,相对距离
node.style.left = e.clientX - offsetX + 'px';
node.style.top = e.clientY - offsetY + 'px';
mouseup
取消拖拽
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#div1{width: 100px; height: 100px; background-color: red; position: absolute;}</style><script>window.onload = function(){var oDiv = document.getElementById("div1");oDiv.onmousedown = function(ev){var e = ev || window.event;var offsetX = e.clientX - oDiv.offsetLeft;var offsetY = e.clientY - oDiv.offsetTop;//被拖拽物体保持相对距离和鼠标移动document.onmousemove = function(ev){var e = ev || window.event;oDiv.style.left = e.clientX - offsetX + 'px';oDiv.style.top = e.clientY - offsetY + 'px';}}//取消拖拽document.onmouseup = function(){document.onmousemove = null;}}</script>
</head>
<body><div id="div1"></div>
</body>
</html>
将此封装为一个函数:
问题:此拖拽是可以随意出界的
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#div1{width: 100px; height: 100px; background-color: red; position: absolute;}</style><script>window.onload = function(){var oDiv = document.getElementById("div1");drag(oDiv);//此拖拽是可以随意出界的}//封装拖拽函数function drag(node){node.onmousedown = function(ev){var e = ev || window.event;var offsetX = e.clientX - node.offsetLeft;var offsetY = e.clientY - node.offsetTop;//被拖拽物体保持相对距离和鼠标移动document.onmousemove = function(ev){var e = ev || window.event;node.style.left = e.clientX - offsetX + 'px';node.style.top = e.clientY - offsetY + 'px';}}//取消拖拽document.onmouseup = function(){document.onmousemove = null;}}</script>
</head>
<body><div id="div1"></div>
</body>
</html>
修改版:
window.onload = function(){var oDiv = document.getElementById("div1"); oDiv.onmousedown = function(ev){var e = ev || window.event;var offsetX = e.clientX - oDiv.offsetLeft;var offsetY = e.clientY - oDiv.offsetTop;//被拖拽物体保持相对距离和鼠标移动document.onmousemove = function(ev){var e = ev || window.event;var l = e.clientX - offsetX;var t = e.clientY - offsetY;//限制出界if(l <= 0){l = 0;}var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;if(l >= windowWidth - oDiv.offsetWidth){l = windowWidth - oDiv.offsetWidth;}if(t <=0){t = 0;}var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;if(t >= windowHeight - oDiv.offsetHeight){t = windowHeight - oDiv.offsetHeight;}oDiv.style.left = l + 'px';oDiv.style.top = t + 'px';}}//取消拖拽document.onmouseup = function(){document.onmousemove = null;}}
修改版封装:
window.onload = function(){var oDiv = document.getElementById("div1");limit(oDiv);}function limit(node){node.onmousedown = function(ev){var e = ev || window.event;var offsetX = e.clientX - node.offsetLeft;var offsetY = e.clientY - node.offsetTop;//被拖拽物体保持相对距离和鼠标移动document.onmousemove = function(ev){var e = ev || window.event;var l = e.clientX - offsetX;var t = e.clientY - offsetY;//限制出界if(l <= 0){l = 0;}var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;if(l >= windowWidth - node.offsetWidth){l = windowWidth - node.offsetWidth;}if(t <=0){t = 0;}var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;if(t >= windowHeight - node.offsetHeight){t = windowHeight - node.offsetHeight;}node.style.left = l + 'px';node.style.top = t + 'px';}}//取消拖拽document.onmouseup = function(){document.onmousemove = null;}}
封装到tool.js中实操:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#div1{width: 100px; height: 100px; background-color: red; position: absolute;}#div2{width: 100px; height: 100px; background-color: blue; position: absolute; left: 400px;}</style><script src="tool.js"></script><script>window.onload = function(){var oDiv1 = document.getElementById("div1");var oDiv2 = document.getElementById("div2");limitDrag(oDiv1);drag(oDiv2);}</script>
</head>
<body><div id="div1"></div><div id="div2"></div>
</body>
</html>
事件委托
给5个<li>添加点击事件,增加一个按钮,按钮的作用是添加节点,但是新添加的节点是无法拥有<li>的点击事件的,解决这个问题需要使用到事件委托这个概念
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script>window.onload = function(){var oUl = document.getElementById("ul1");var aLis = oUl.getElementsByTagName("li");//添加点击事件for(var i = 0; i < aLis.length; i++){aLis[i].onclick = function(){this.style.backgroundColro = "red";}}/* 1、给五个li标签添加一模一样的点击事件造成浪费2、新增节点是没有点击事件的,因为点击事件的循环已经结束了*/var obtn = document.getElementById("btn1");var i = 6;obtn.onclick = function(){var newNode = document.createElement("li");newNode.innerHTML = i++ * 1111;oUl.appendChild(newNode);}}</script>
</head>
<body><button id="btn1">新增节点</button><ul id="ul1"><li>1111</li><li>2222</li><li>3333</li><li>4444</li><li>5555</li></ul>
</body>
</html>
委托
A委托B去买饭
A发布任务 委托方
B执行任务 代理方
事件委托实现步骤
1、找到当前节点的父节点或者祖先节点
2、将时间添加到你找到的这个父节点或者祖先节点上
3、找到触发对象,判断触发对象是否是想要的触发对象,进行后续的操作
通过事件委托修改版
通过ul给li添加点击事件,解决了浪费问题同时也解决了无法给新增节点添加点击事件的问题
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script>window.onload = function(){var oUl = document.getElementById("ul1");oUl.onclick = function(ev){var e = ev || window.event;var target = e.target || window.event;if(target.nodeName.toLowerCase() == "li"){target.style.backgroundColor = "red";}}var obtn = document.getElementById("btn1");var i = 6;obtn.onclick = function(){var newNode = document.createElement("li");newNode.innerHTML = i++ * 1111;oUl.appendChild(newNode);}}</script>
</head>
<body><button id="btn1">新增节点</button><ul id="ul1"><li>1111</li><li>2222</li><li>3333</li><li>4444</li><li>5555</li></ul>
</body>
</html>
Event事件监听器
1、传统事件绑定
<1>重复添加,覆盖
<2>不能精确的删除事件上的某一个函数
<script>//传统的事件绑定window.onload = function(){var oBtn = document.getElementById("btn1");oBtn.onclick = function(){alert("点击1");}oBtn.onclick = function(){alert("点击2");} }function show(){alert("hello world");}</script><body><button id="btn1">按钮</button>
</body>
2、事件监听器(低版本IE浏览器下不兼容)
addEventListener
格式:node.addEventListener("click");
参数:
第一个参数:事件类型
第二个参数:绑定函数
第三个参数:布尔值 true 事件捕获
false 事件冒泡 默认
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div{padding: 50px;}#div1{background-color: red;}#div2{background-color: yellow;}#div3{background-color: blue;}</style><script>window.onload = function(){var aDivs = document.getElementsByTagName("div");// for(var i = 0; i < aDivs.length; i++){// aDivs[i].addEventListener("click",function(){// alert(this.id);// },false); //点击蓝色部分,div3 → div2 → div1,由里向外;此时为事件冒泡// }for(var i = 0; i < aDivs.length; i++){aDivs[i].addEventListener("click",function(){alert(this.id);},true); //点击蓝色部分,div1 → div2 → div3,由外向里;此时为事件捕获}}</script>
</head>
<body><div id="div1"><div id="div2"><div id="div3"></div></div></div>
</body>
</html>
removeEventListener( )
格式:node.removeEventListener
参数:
第一个参数:事件类型
第二个参数:删除函数名字
<script>window.onload = function(){var oBtns = document.getElementsByTagName("button");oBtns[1].addEventListener("click",function(){alert("原有的函数");},false);oBtns[0].onclick = function(){oBtns[1].addEventListener("click",show,false);}oBtns[2].onclick = function(){oBtns[1].removeEventListener("click",show);}}function show(){alert("hello world");}</script><body><button>添加函数</button><button>按钮</button><button>删除函数</button>
</body>
2.1、事件监听器(兼容版)
attachEvent( )
detaEvent( )
function addEvent(node, evenType, funcName){if(node.addEventListener){node.addEventListener(evetnType, funcName, false);}else{node.attachEvent("on" + evenType, funcName);}}function removeEvent(node, evenType, funcName){if(node.removeEventListener){node.removeEventListener(evenType, funcName);}else{node.detaEvent("on" + evenType, funcName);}}
动态生成表格
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#t1 tr td{width: 300px; height: 30px;}.box0{background-color: red;}.box1{background-color: blue;}</style><script>window.onload = function(){var oRow = document.getElementById("row");var oCol = document.getElementById("col");var oBtn = document.getElementById("btn1");var oT1 = document.getElementById("t1");//给表格上的删除按钮添加事件委托oT1.onclick = function(ev){var e = ev || window.event;var target = e.target || window.event.srcElement;if(target.nodeName.toLowerCase() == "button"){oT1.removeChild(target.parentNode.parentNode);}}oBtn.onclick = function(){if(!oRow.value || !oCol.value){alert("请输入对应的行列,生成表格");}else{//行for(var i = 0; i < oRow.value; i++){var oTr = document.createElement("tr");oTr.className = "box" + (i % 2);for(var j = 0; j < oCol.value; j++){var oTd = document.createElement("td");oTr.appendChild(oTd);}//添加一个删除按钮var oClose = document.createElement("td");oClose.innerHTML = "<button>删除</button>";oTr.appendChild(oClose);oT1.appendChild(oTr);}}}}</script>
</head>
<body><input type="text" placeholder="行" id="row"/><input type="text" placeholder="列" id="col"/><button id="btn1">生成</button><table id="t1" border="1"></table>
</body>
</html>
放大镜案例
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0" ><title>Document</title><style>#small{width: 405px; height: 270px; position: absolute; left: 50px; top: 100px;}#small img{width: 100%; height: 100%;}#mark{display: none; width: 100px; height: 100px; background-color: white; opacity: 0.5; filter: alpha(opacity=50); position: absolute; left: 0px; top: 0px;}#big{/* display: none; */ width: 200px; height: 200px; border: 1px solid black; left: 1300px; top:100px; position: absolute; /* overflow: hidden; */ }#big img{width: 810px; height: 540px; position: absolute; left: 0px; top: 0px;}</style><script>window.onload = function(){var oSmall = document.getElementById("small");var oBig = document.getElementById("big");var oMark = document.getElementById("mark");var oBigImg = oBig.getElementsByTagName("img")[0];oSmall.onmouseover = function(){oMark.style.display = 'block';oBig.style.display = 'block';}oSmall.onmouseout = function(){oMark.style.display = 'none';oBig.style.display = 'none';}oSmall.onmousemove = function(ev){var e = ev || window.event; //拿到事件对象var l = e.clientX - oSmall.offsetLeft - 50;var t = e.clientY - oSmall.offsetTop - 50;if(l < 0){l = 0;}else if(l >= 305){l = 305;}if(t < 0){t = 0;}else if(t >= 170){t = 170;}oMark.style.left = l + 'px';oMark.style.top = t + 'px';/* 右边图片的移动方式,左边遮罩层如何移动? 右边图片,反方向对应倍数移动 */oBigImg.style.left = l * -2 + 'px';oBigImg.style.top = t * -2 + 'px';}}</script>
</head>
<body><div id="small"><img src="./images/sxx2.jpg" alt=""><div id="mark"></div></div><div id="big"><img src="./images/sxx2.jpg" alt=""></div>
</body>
</html>
JavaScript 事件和事件类型相关推荐
- JavaScript 中的事件类型1(读书笔记思维导图)
Web 浏览器中可能发生的事件有很多类型.如前所述,不同的事件类型具有不同的信息,而" DOM3级事件"规定了以下几类事件. UI(User Interface,用户界面)事件:当 ...
- JavaScript 中的事件类型3(读书笔记思维导图)
Web 浏览器中可能发生的事件有很多类型.如前所述,不同的事件类型具有不同的信息,而" DOM3级事件"规定了以下几类事件. UI(User Interface,用户界面)事件:当 ...
- JavaScript 中的事件类型2(读书笔记思维导图)
Web 浏览器中可能发生的事件有很多类型.如前所述,不同的事件类型具有不同的信息,而" DOM3级事件"规定了以下几类事件: UI(User Interface,用户界面)事件:当 ...
- JavaScript 中的事件类型5(读书笔记思维导图)
Web 浏览器中可能发生的事件有很多类型.如前所述,不同的事件类型具有不同的信息,而" DOM3级事件"规定了以下几类事件. UI(User Interface,用户界面)事件:当 ...
- JavaScript 中的事件类型4(读书笔记思维导图)
Web 浏览器中可能发生的事件有很多类型.如前所述,不同的事件类型具有不同的信息,而" DOM3级事件"规定了以下几类事件. UI(User Interface,用户界面)事件:当 ...
- 「前端面试题系列7」Javascript 中的事件机制(从原生到框架)
前言 这是前端面试题系列的第 7 篇,你可能错过了前面的篇章,可以在这里找到: 理解函数的柯里化 ES6 中箭头函数的用法 this 的原理以及用法 伪类与伪元素的区别及实战 如何实现一个圣杯布局? ...
- 【初窥javascript奥秘之事件机制】论“点透”与“鬼点击”
前言 最近好好的研究了一番移动设备的点击响应速度,期间不断的被自己坑,最后搞得焦头烂额,就是现在可能还有一些问题,但是过程中感觉自己成长不少, 最后居然感觉对javascript事件机制有了更好的认识 ...
- DOM笔记(五):JavaScript的常见事件和Ajax小结
一.常见事件类型 1.鼠标事件 事件名称 说明 onclick 鼠标单击时触发 ondbclick 鼠标双击时触发 onmousedown 鼠标左键按下时触发 onmouseup 鼠标释放时触发 on ...
- 理解JavaScript中的事件
在很多语言的学习中,"事件"都是一个比较难理解,但是又是一个很重要的概念.JavaScript中的事件处理也是一样,正因为有了事件处理,才会出现Ajax拖动的效果.本文就讨论一下J ...
最新文章
- Python+pandas计算数据相关系数(person、Kendall、spearman)
- Android Studio 使用Gradle引入第三方库文件的总结
- torch yolov3训练性能优化
- Active Diretory 全攻略(五)--规划和建立组
- matlab神经网络1:功能特色
- _欧冠F组第1轮,拉齐奥3-1大胜多特蒙德
- html js php 混编,Razor标记语言和HTML,js混编
- [Asp.Net Core轻量级Aop解决方案]AspectCore Project 介绍
- Oracle数据库模式对象管理问题与解决
- SOAP协议初级指南(9)
- 腾讯的全球地址数据文件及Xml->Json的处理
- light4java_Light Weight Component Library for Java
- Linux进程间通信之管道(pipe)、命名管道(FIFO)与信号(Signal)
- QQ浏览器11版,中文输入法定位错误
- 背包问题九讲 2.0 beta1.1
- 【JY】浅析各动力求解算法及其算法数值阻尼(人工阻尼)
- 深度对比Soul、觅伊,两款社交软件区别在哪?
- 齐兴皓 团队项目(任务五):项目回顾
- 柱坐标系与直角坐标系的转换
- mysql 存储过程中 if else的使用 和赋值方式