在下面的jsfiddle中我试图将黄色和红色圆圈设置为最初出现在中心,而不是移动到光标的初始假定位置 - 这是(0,0)因为光标还没有出现在页面的实际屏幕上(如果我猜对了)。
http://jsfiddle.net/fhmkf/220/
我有没有办法定义光标的初始位置 - 就是在计算(window).mousemove(function(e){...
时 - 尤其是e.pageX
和e.pageY
?
js看起来像这样:
var Circle = function(container, follower, r){
var center = {
x: $(container).width()/2 - r,
y: $(container).height()/2 - r
};
var distanceThreshold = $(container).width()/2 - r;
var mouseX = 0, mouseY = 0;
$(window).mousemove(function(e){
var d = {
x: e.pageX - center.x,
y: e.pageY - center.y
};
var distance = Math.sqrt(d.x*d.x + d.y*d.y);
if (distance < distanceThreshold) {
mouseX = e.pageX;
mouseY = e.pageY;
} else {
mouseX = d.x / distance * distanceThreshold + center.x;
mouseY = d.y / distance * distanceThreshold + center.y;
}
});
// 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) / 2;
yp += (mouseY - yp) / 2;
follower.css({left:xp, top:yp});
}, 30);
};
var c1 = new Circle(".container", "#follower", 15);
var c2 = new Circle(".container2", "#follower2", 25);