【问题标题】:How do move div with mouse pointer on hover?如何在悬停时使用鼠标指针移动 div?
【发布时间】:2013-12-30 17:11:37
【问题描述】:
<div class="moveAble" style="position: absolute;">
<div class="info"><img src="https://pbs.twimg.com/profile_images/1498221863/Jodis_Gifts_logo_hi_res_normal.jpg" alt="info" /></div>
</div>

$(document).ready(function(){
      $('div.moveAble').mousemove(function(e){
            var y = e.pageY;
            var x = e.pageX;
            $('div.moveAble').css({'top': y}); 
            $('div.moveAble').css({'left': x});

      });
    });

上面的代码不能正常工作,当我移动鼠标指针时,它只在底部和右侧移动,而不是在顶部和左侧。并且 div 的移动也不顺畅。 我该如何解决这个问题以使其正常工作。

DEMO here

【问题讨论】:

  • 你必须使用 .animate 来制作流畅的瞬间
  • 问题是您正在处理 div 本身的 mousemove 事件,但是当您将鼠标向上移动到左侧时,它不再位于 div 上方。
  • @ManishJangirBlogaddition.com - 不,你不知道:有很多移动流畅的网站根本不使用 jQuery,所以不要使用 .animate()
  • 而不是$('div.moveAble').mousemove 使用$(document).mousemove
  • 喜欢这个jsfiddle.net/wUAGP/435 ?

标签: javascript jquery html css


【解决方案1】:

我想这就是你想要的效果http://jsfiddle.net/wUAGP/440/

$(document).ready(function(){
  var $moveable = $('.moveAble');
  $(document).mousemove(function(e){
      $moveable.css({'top': e.pageY,'left': e.pageX});
  });
});

感谢@nnnnnn提到$moveable的缓存

【讨论】:

  • 不需要将事件绑定到文档。您可以计算鼠标偏移量并计算鼠标方向和移动图像。
  • @antindexer,最好将document 用于mousemove 事件,但要根据其他用户输入启用/禁用侦听器(例如mousedownmouseup)。
  • @antindexer,在为该图像触发mousemove 事件之前,图像也不会随光标移动(即鼠标在该图像上移动)
【解决方案2】:
$(document).ready(function(){
      $('div.moveAble').mousemove(function(e){
            var y = e.pageY;
            var x = e.pageX;
            $('.moveAble').css('top', y-20).css('left', x-20);
      });
    });

看这个$('.moveAble').css('top', y-20).css('left', x-20);

你的鼠标就在边框上,所以你需要移动它。

小提琴:http://jsfiddle.net/wUAGP/436/

【讨论】:

  • 这比原来的版本更好,但是如果你快速移动鼠标,它仍然会离开 div,因此 div 将停止跟随鼠标。 (可能是理想的效果?)
  • 是的,我已经看到了,用 "$('.moveAble').css('top', y - ($(this). height() / 2)).css('left', x- ($(this).width() / 2)); " (jsfiddle.net/wUAGP/442),但是如果用户快速移动它仍然是一样的。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多