本文收集整理自网上。
一,判断滚动条的方向,利用闭包首先保存滚动条的位置,然后当滚动时候不断更新滚动初始值,然后通过差指判断方向
1 function scroll(fn) { 2 //利用闭包判断滚动条滚动的方向 3 var beforeScrollTop = document.body.scrollTop, 4 fn = fn || function() {}; 5 window.addEventListener("scroll", function() { 6 var afterScrollTop = document.body.scrollTop, 7 delta = afterScrollTop - beforeScrollTop; 8 if (delta === 0) return false; 9 fn(delta > 0 ? "down" : "up"); 10 beforeScrollTop = afterScrollTop; 11 }, false); 12 } 13 scroll(function(direction) { console.log(direction) });
二,判断鼠标的移动方向
1 function direction() { 2 var lastX = null, 3 lastY = null; 4 window.addEventListener("mousemove", function(event) { 5 var curX = event.clientX, 6 curY = event.clientY, 7 direction = ''; 8 // console.info(event); 9 // console.info(event.clientX); 10 // console.info(event.clientY); 11 // 初始化坐标 12 if (lastX == null || lastY == null) { 13 lastX = curX; 14 lastY = curY; 15 return; 16 } 17 if (curX > lastX) { 18 direction += 'X右,'; 19 } else if (curX < lastX) { 20 direction += 'X左,'; 21 } 22 if (curY > lastY) { 23 direction += 'Y下'; 24 } else if (curY < lastY) { 25 direction += 'Y上'; 26 } 27 lastX = curX; 28 lastY = curY; 29 //console.info(direction); 30 document.getElementById("test").innerText = direction; 31 }) 32 }
三,判断鼠标进入和出去某Dom元素的方式,这种没有利用闭包原理
1 var gaga = function(wrap) { 2 var wrap = document.getElementById(wrap); 3 var hoverDir = function(e) { 4 var w = wrap.offsetWidth, 5 h = wrap.offsetHeight, 6 x = (e.clientX - wrap.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1), 7 y = (e.clientY - wrap.offsetTop - (h / 2)) * (h > w ? (w / h) : 1), 8 // 上(0) 右(1) 下(2) 左(3) 9 direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4, 10 eventType = e.type, 11 dirName = new Array('上方', '右侧', '下方', '左侧'); 12 if (e.type == 'mouseover' || e.type == 'mouseenter') { 13 wrap.innerHTML = dirName[direction] + '进入'; 14 } else { 15 wrap.innerHTML = dirName[direction] + '离开'; 16 } 17 } 18 if (window.addEventListener) { 19 wrap.addEventListener('mouseover', hoverDir, false); 20 wrap.addEventListener('mouseout', hoverDir, false); 21 } else if (window.attachEvent) { 22 wrap.attachEvent('onmouseenter', hoverDir); 23 wrap.attachEvent('onmouseleave', hoverDir); 24 } 25 }
本文结束。