2.js的兼容性问题
ev||event
offsetParent
事件绑定(事件流的机制;事件委托)
鼠标滚轮事件
非火狐:onmousewhell(dom0)
ev.whellDelta(滚轮方向)
上:正
下:负
testNode.onmousewheel=function(ev){ var ev=ev||event; console.log(wheelDelta); }
火狐: DOMMouseScroll(dom2)
ev.detail(滚轮方向)
上:负
下:正
怎么取消事件的默认行为
dom0:return false
dom2:ev.preventDefault()
视口尺寸的获取
滚动条滚动的距离
var testNode=document.querySelector("#test"); if(testNode.addEventListener){ testNode.addEventListener("DOMMouseScroll",function(ev){ var ev=ev||event; console.log(ev.detail); }) }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #test{ 200px; height: 200px; background: pink; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } </style> </head> <body> <div id="test"></div> </body> <script type="text/javascript"> var testNode=document.querySelector("#test"); alert(testNode.addEventListener); if(testNode.addEventListener){ testNode.addEventListener("DOMMouseScroll",function(){ console.log("火狐在滚"); }) } testNode.onmousewheel=function(){ console.log("非火狐在滚"); } </script> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #test{ 100%; height: 200px; background: pink; } </style> </head> <body "> <div id="test"></div> </body> <script type="text/javascript"> window.onload=function(){ var testNode = document.querySelector("#test"); if(testNode.addEventListener){ testNode.addEventListener("DOMMouseScroll",fn); } testNode.onmousewheel=fn; function fn(ev){ ev=ev||event; var dir=""; if(ev.wheelDelta){ dir = ev.wheelDelta>0?"up":"down"; } if(ev.detail){ dir = ev.detail<0?"up":"down"; } /* 对样式进行设置(特殊性最高) node.style.height 对样式进行读取 node.style.height (读不到css样式表中属性的) 读取一般通过api来进行读取 testNode.getComputedStyle() */ switch (dir){ case "up": testNode.style.height = testNode.offsetHeight -10+"px"; //... break; case "down": testNode.style.height = testNode.offsetHeight +10+"px"; //.... break; } //禁止事件的默认行为 dom2 if(ev.preventDefault){ ev.preventDefault(); } //禁止事件的默认行为 dom0 return false; } } </script> </html>