我正在使用以下脚本来检测鼠标/光标何时接近div。好的,它可以工作,但是现在我以像素为单位测量距离。我要测量的距离是vh单位。
$('body').mousemove(function(event) {
if (isNear($('.test-arrowRight'), 550, event)) {
$('.test-arrowRight').css('background', 'url(www.background-url.com)');
} else {
$('.test-arrowRight').css('background', 'url(www.background-url.com)');
};
});
function isNear($element, distance, event) {
var left = $element.offset().left - distance,
top = $element.offset().top - distance,
right = left + $element.width() + (2 * distance),
bottom = top + $element.height() + (2 * distance),
x = event.pageX,
y = event.pageY;
return (x > left && x < right && y > top && y < bottom);
}
答案 0 :(得分:1)
只需找出视口尺寸并相应调整即可。像
function isNear($element, distance, event) {
var vw = $(window).width(),
vh = $(window).height(),
left = $element.offset().left/vw*100 - distance,
top = $element.offset().top/vh*100 - distance,
right = left + $element.width()/vw*100 + (2 * distance),
bottom = top + $element.height()/vh*100 + (2 * distance),
x = event.pageX/vw*100,
y = event.pageY/vh*100;
return (x > left && x < right && y > top && y < bottom);
}