1

我有一个设置,其中 div 跟随屏幕周围的光标(当前 2 个 div,但这将是内容管理,因此很快会有几十个),理想情况下每个 div 以不同的速度跟随光标(最大速度为 50) .
jsfiddle:http : //jsfiddle.net/neal_fletcher/nEKgN/

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

var follower = $(".stuck");
var xp = 0, yp = 0;
var loop = setInterval(function(){
    // higher is slower
    xp += (mouseX - xp) / 30;
    yp += (mouseY - yp) / 30;
    follower.css({left:xp, top:yp});

}, 30);
});

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

var follower = $(".stuck-2");
var xp = 0, yp = 0;
var loop = setInterval(function(){
    // higher is slower
    xp += (mouseX - xp) / 20;
    yp += (mouseY - yp) / 20;
    follower.css({left:xp, top:yp});

}, 30);
});

在上面的示例中,我必须给每个 div 一个不同的类(或 ID)来为每个 div 设置不同的速度,但就像我说的那样,这将是内容管理的,这将是不可能的,理想情况下我会喜欢所有 div 具有相同的类并随机化每个 div 的速度,最大速度为 50。不知道这是否可能?任何建议将不胜感激!

4

1 回答 1

4

用于.each迭代追随者并为每个追随者分配一个“跳跃”值:

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

    var followers = $(".stuck");

    followers.each(function () {
        var follower = $(this),
            jump = 1 + (Math.random() * 50),
            xp = 0,
            yp = 0;

        var loop = setInterval(function () {
            // higher is slower
            xp += (mouseX - xp) / jump;
            yp += (mouseY - yp) / jump;
            follower.css({
                left: xp,
                top: yp
            });
        }, 30);
    });

});

这是一个演示:http: //jsfiddle.net/Nxdm7/

于 2013-08-14T20:56:42.573 回答