赞
踩
所有dom元素,浏览器都会为之绑定一些默认的事件行为,比如(onclick,onmouseover,onmouseout,onmouseleave,onmouseenter,onscroll,keyup,keydown…)
我们可以为这些默认的行为绑定对应的方法,让其行为在触发的时候,执行我们绑定的方法.
0级事件也就是我们平常直接用的 (例如: div.onclick = function(e){ e =e || window.event } )直接给元素行为绑定方法.
div.addEventListener(‘click’,function(e){ e=e||window.event },fasle);
第一个参数:事件行为
第二个参数:事件行为对应的方法
第三个参数:false(默认) 冒泡阶段执行对应方法…true:捕获阶段执行方法
<!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> <style> * { margin: 0; padding: 0; box-sizing: border-box; } .box { position: relative; width: 500px; height: 500px; font-size: 16px; border: 1px solid tomato; margin: 100px auto; cursor: pointer; } .content { position: absolute; top: 0px; left: 0px; width: 200px; height: 200px; line-height: 200px; text-align: center; background-color: yellow; opacity: 0.8; filter: alpha(opacity=80); border: 1px dashed red; cursor: move; } </style> </head> <body> <div class="box" id="box"> <div class="content" id="content" style="display: none"> 点击详情,进行登录 </div> </div> </body> </html> <script type="text/javascript" charset="utf-8"> (function () { var box = document.getElementById("box"), content = document.getElementById('content'); // 设置content位置 function setOption(e) { var clientX = e.clientX, clientY = e.clientY, boxLeft = this.offsetLeft, boxTop = this.offsetTop, contentW = content.offsetWidth, contentH = content.offsetHeight, left = clientX - boxLeft - contentW / 2, top = clientY - boxTop - contentH / 2; // 设定边界值 var minL = 0, minT = 0; var maxL = this.offsetWidth - contentW, maxT = this.offsetHeight - contentH; if (left < minL) { left = minL } else if (left > maxL) { left = maxL } if (top < minT) { top = minT } else if (top > maxT) { top = maxT } content.style.left = left + "px"; content.style.top = top + "px"; }; // 触发鼠标移入事件(onmouseover) // onmouseover 没有阻止事件冒泡传播, // onouseenter 阻止了事件冒泡传播 box.onmouseenter = function (e) { // window.event 兼容ie6-8 e = e || window.event; content.style.display = "block"; }; box.onmousemove = function (e) { e = e || window.event; setOption.call(this, e); }; // 触发鼠标移除事件(onmouseout) box.onmouseleave = function (e) { e = e || window.event; content.style.display = "none"; }; })(); </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。