利用闭包判断Dom元素和滚动条的方向

时间:2023-03-09 06:15:57
利用闭包判断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 === ) return false;
fn(delta > ? "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 / )) * (w > h ? (h / w) : ),
y = (e.clientY - wrap.offsetTop - (h / )) * (h > w ? (w / h) : ),
// 上(0) 右(1) 下(2) 左(3)
direction = Math.round((((Math.atan2(y, x) * ( / Math.PI)) + ) / ) + ) % ,
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);
}
}

本文结束。