本文实例讲述了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 "_blank" href="//www.jb51.net/Special/85.htm">javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》希望本文所述对大家JavaScript程序设计有所帮助。