首页 > 解决方案 > Mousemove issue [jQuery]

问题描述

I've just created #element and #box which detect if it's out of the viewport. If so, it should go above the cursor but here's my issue. When #box is out of the viewport it starts acting weird by flashing over and over. Hope you guys can help me. Cheers.

var box = $("#box");
var element = $("#element");
var PAGEX;
var PAGEY;
var elementTop;
var elementBottom;
var windowHeight;

element.bind({
mousemove: function (e) {
box.show();

PAGEX = e.pageX;
PAGEY = e.pageY;

elementTop = box.offset().top;
elementBottom = elementTop + box.outerHeight();
windowHeight = $(window).height();

if(elementBottom > windowHeight)
{
  box.css({
    top: PAGEY - 65,
    left: PAGEX + 15
  })
}
else
{
  box.css({
    top: PAGEY + 15,
    left: PAGEX + 15
  })
}

},
mouseleave: function () {
box.hide();
}
})

JSFiddle

标签: javascriptjquery

解决方案


这里的问题是您正在根据实际框位置进行视口外检查,而不是基于鼠标移动的位置。因此,这在盒子第一次移出视口时有效 - 您将其调整回内部。但是,下次鼠标移动时,您的框就安全地位于视口内。因此,您的检查会根据鼠标位置对其进行调整,并将其放在视口之外。下一次鼠标移动时,计算就会起作用,然后它会被调整回内部,依此类推。

解决方法是改变这一点:

if(elementBottom > windowHeight)

对此:

if(PAGEY + 15 + box.outerHeight() > windowHeight)

因此,它始终根据目标位置的位置而不是其当前位置的位置来计算视口外。


推荐阅读