简体   繁体   English

根据鼠标位置移动div

[英]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. 我正在尝试创建一个垂直列表,并在该列表上生效,当您将鼠标悬停在垂直列表上时,一个单独的“游标” div应该沿着该列表垂直向上和向下移动,并与指针水平对齐。

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: 然后用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. 所有这些工作,但是光标div不能与我的鼠标指针完美对齐。 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/ 这是一个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. 但是,如果我正确理解了您的代码,我相信您不能只是在.sidebarnav mouseover更新.cursor的位置-相反,您需要始终在mousemove上更新其位置。

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. Edit2:我认为,使用mouseentermouseleave也可能会有更好的结果。 I think over/out triggers as soon as you hover a child of the element as well. 我认为,一旦您将元素的一个子元素也悬停了,就会触发结束/结束触发器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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