简体   繁体   中英

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

The problem here is that you are doing your out-of-viewport check against the actual box location, rather than the location based on the mousemove. So, this works the first time the box would move out of the viewport - you adjust it back inside. But, the next time the mouse moves, your box is safely inside the viewport. So your check adjusts it based on the mouse position, and it gets put outside the viewport. The next time the mouse moves, the calculation works, and it gets adjusted back inside, and so on.

The fix is to change this:

if(elementBottom > windowHeight)

To this:

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

So that it is always calculating the out-of-viewport based on where the target location would be, and not where its current location is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM