javascript 如何在悬停时使用鼠标指针移动 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20836276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do move div with mouse pointer on hover?
提问by Arya Mehta
<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});
});
});
Above code is not working properly, as i move mouse pointer it move in bottom and right direction only and not top and left. and div movement is also not smooth. How do i fix this to make it work.
上面的代码工作不正常,当我移动鼠标指针时,它只在底部和右侧移动,而不是顶部和左侧。而且div的运动也不流畅。我如何解决这个问题以使其正常工作。
回答by
I suppose this is the effect you wanted http://jsfiddle.net/wUAGP/440/
我想这就是你想要的效果 http://jsfiddle.net/wUAGP/440/
$(document).ready(function(){
var $moveable = $('.moveAble');
$(document).mousemove(function(e){
$moveable.css({'top': e.pageY,'left': e.pageX});
});
});
Thanks to @nnnnnnfor mentioning the caching of $moveable
感谢@nnnnnn提到缓存$moveable
回答by BENARD Patrick
$(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);
});
});
Look this $('.moveAble').css('top', y-20).css('left', x-20);
看看这个 $('.moveAble').css('top', y-20).css('left', x-20);
Your mouse is just at border, so you need to shift it.
你的鼠标刚好在边界,所以你需要移动它。
fiddle : http://jsfiddle.net/wUAGP/436/