0

在下面的 jsfiddle 中,我试图让黄色和红色圆圈最初出现在中心,而不是移动到光标的初始假定位置- 这是 (0,0),因为光标尚未在实际屏幕中页面(如果我猜对了)。

http://jsfiddle.net/fhmkf/220/

有没有一种方法可以定义光标的初始位置 - 即在计算时(window).mousemove(function(e){...- 特别是e.pageXand 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);
4

0 回答 0