我有一个圆形的div,它跟随你的鼠标使用Javascript,但我希望它在遇到容器div的边缘时停止。我该怎么办?这是使用的Javascript:
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
请帮助,谢谢!
答案 0 :(得分:3)
您需要确定移动元素的限制......
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
是光标的大小