JS实现利用闭包判断Dom元素和滚动条的方向示例
我站在山顶上 人气:0本文实例讲述了JS实现利用闭包判断Dom元素和滚动条的方向。分享给大家供大家参考,具体如下:
一、判断滚动条的方向,利用闭包首先保存滚动条的位置,然后当滚动时候不断更新滚动初始值,然后通过差指判断方向
function scroll(fn) { //利用闭包判断滚动条滚动的方向 var beforeScrollTop = document.body.scrollTop, fn = fn || function() {}; window.addEventListener("scroll", function() { var afterScrollTop = document.body.scrollTop, delta = afterScrollTop - beforeScrollTop; if (delta === 0) return false; fn(delta > 0 ? "down" : "up"); beforeScrollTop = afterScrollTop; }, false); } scroll(function(direction) { console.log(direction) });
二、判断鼠标的移动方向
function direction() { var lastX = null, lastY = null; window.addEventListener("mousemove", function(event) { var curX = event.clientX, curY = event.clientY, direction = ''; // console.info(event); // console.info(event.clientX); // console.info(event.clientY); // 初始化坐标 if (lastX == null || lastY == null) { lastX = curX; lastY = curY; return; } if (curX > lastX) { direction += 'X右,'; } else if (curX < lastX) { direction += 'X左,'; } if (curY > lastY) { direction += 'Y下'; } else if (curY < lastY) { direction += 'Y上'; } lastX = curX; lastY = curY; //console.info(direction); document.getElementById("test").innerText = direction; }) }
三、判断鼠标进入和出去某Dom元素的方式,这种没有利用闭包原理
var gaga = function(wrap) { var wrap = document.getElementById(wrap); var hoverDir = function(e) { var w = wrap.offsetWidth, h = wrap.offsetHeight, x = (e.clientX - wrap.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1), y = (e.clientY - wrap.offsetTop - (h / 2)) * (h > w ? (w / h) : 1), // 上(0) 右(1) 下(2) 左(3) direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4, eventType = e.type, dirName = new Array('上方', '右侧', '下方', '左侧'); if (e.type == 'mouseover' || e.type == 'mouseenter') { wrap.innerHTML = dirName[direction] + '进入'; } else { wrap.innerHTML = dirName[direction] + '离开'; } } if (window.addEventListener) { wrap.addEventListener('mouseover', hoverDir, false); wrap.addEventListener('mouseout', hoverDir, false); } else if (window.attachEvent) { wrap.attachEvent('onmouseenter', hoverDir); wrap.attachEvent('onmouseleave', hoverDir); } }
希望本文所述对大家JavaScript程序设计有所帮助。
加载全部内容