简体   繁体   中英

moving a div according to mouse position

I am trying to create and effect where you have a vertical list, and when you hover it with your mouse, a separate "cursor" div should travel up and down vertically along this list, horizontally aligned with your pointer.

I am using this code:

$(document).mousemove( function(e) {
   mouseY = e.pageY;
   mouseX = e.pageX;
   translateY = 'translateY(' + mouseY + 'px)';
   translateX = 'translateX(' + mouseX + 'px)';
});

Then with jQuery:

$(".sidebarnav").mouseover(function(){
  $('.sidebarnav .cursor').css({'transform': translateY});
});

All this kind of work, but the cursor div does not perfectly align with my mouse pointer. It does if you move real slow and with precision, but it doesn't if you move a bit faster. Is there any technical reason to this lack of precision, or is my code just wrong?

Here is a jsfiddle http://jsfiddle.net/txks3wtj/

A fiddle would definitely help. But if I understand your code correctly I believe you can't just update the .cursor 's position on mouseover of the .sidebarnav - instead you need to update its position on mousemove ie all the time.

Since you don't want the cursor to move when not hovering the sidebar you'd need to keep track of whether or not it is hovered. Something like:

var isOver = false;

$('.sidebarnav').mouseover(function () {
    isOver = true;
}).mouseout(function () {
    isOver = false;
});

$(document).mousemove( function(e) {
    mouseY = e.pageY;
    mouseX = e.pageX;
    translateY = 'translateY(' + mouseY + 'px)';
    translateX = 'translateX(' + mouseX + 'px)';

    if (isOver) {
        $('.sidebarnav .cursor').css({'transform': translateY});
    }
});

Untested.

Edit: It would increase performance if you cached your queries as well;

var sidebar = $('.sidebarnav');
var cursor = sidebar.find('.cursor');

Edit2: You may have better results with mouseenter and mouseleave too I think. I think over/out triggers as soon as you hover a child of the element as well.

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