我有一个圆形的div,它使用Javascript跟随您的鼠标,但是当它碰到容器div的边缘时,我希望它停止。我该怎么做?这是使用的Javascript im:

var mouseX = 0, mouseY = 0;
$(document).mousemove(function(e){
mouseX = e.pageX;
mouseY = e.pageY;
});

// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.css({left:xp, top:yp});

}, 30);


这是我到目前为止所拥有的一切:jsFiddle

请帮忙,谢谢!

最佳答案

您需要确定要移动的元素的极限...

var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
$(window).mousemove(function(e){
   mouseX = Math.min(e.pageX, limitX);
   mouseY = Math.min(e.pageY, limitY);
});


其中150是容器的宽度/高度,而15是光标的大小

http://jsfiddle.net/fhmkf/

07-24 09:36