Beispiel: Follow Mouse – Zeitgeber und Mindestabstand

DIV-Elemente verfolgen zeitgesteuert mit einen Mindestabstand den Mauszeiger.

drweb.de - Magazin für Seitenbetreiber

JavaScript-Quelltext

jQuery.noConflict();

jQuery(document).ready(function() {
    var follow   = [];
    var timeDiff = 100;
    var mousePos = {x: 0, y: 0};


    // Absolut positioniertes Div erzeugen und an follow[] sowie
    // HTML Body anhängen.
    function addDiv(color) {
        var el = document.createElement("div");

        el.style.backgroundColor = color;

        el.style.position    = "absolute";
        el.style.left        = 0;
        el.style.top         = 0;

        el.style.margin      = 0;
        el.style.padding     = 0;
        el.style.borderWidth = 0;
        el.style.fontSize    = 0; // IE

        el.style.width       = "40px";
        el.style.height      = "40px";

        follow.push(el);

        document.getElementsByTagName("body")[0].appendChild(el);
    }// addDiv


    function move() {
        // follow[5].pos = follow[4].pos;
        // follow[4].pos = follow[3].pos;
        // ...
        // follow[1].pos = follow[0].pos;
        for(var i = follow.length - 1; i >= 1; i--) {
            follow[i].style.left = follow[i - 1].style.left;
            follow[i].style.top  = follow[i - 1].style.top;
        }

        // follow[0].pos = Aktuelle Position des Mauszeigers im Dokument
        follow[0].style.left = mousePos.x + "px";
        follow[0].style.top  = mousePos.y + "px";
    }// move


    // Divs erzeugen
    addDiv("red");     // follow[0]
    addDiv("green");
    addDiv("blue");
    addDiv("yellow");
    addDiv("aqua");
    addDiv("fuchsia"); // follow[5]


    // Mousemove-Handler
    jQuery(document).mousemove(function(e) {
        // Position ohne "px": 40px -> 40
        var left = parseFloat(follow[0].style.left);
        var top  = parseFloat(follow[0].style.top);


        // Abstand Verfolger zur aktuellen Mausposition
        var distance = Math.sqrt(Math.pow(e.pageX - left, 2) +
                                 Math.pow(e.pageY - top,  2));

        if(distance > 50 ) {
            mousePos.x = e.pageX + 10;
            mousePos.y = e.pageY + 10;
        }
    });// mousemove


    // Zeitgeber starten
    setInterval(move, timeDiff);
});// jQuery(document).ready(function() {