how to get a div to randomly move around a page (using jQuery or CSS)

前端 未结 7 881
旧时难觅i
旧时难觅i 2020-11-29 00:01

I\'ve been doing some Googling to find an answer to this, but I\'ve had no luck. It could be because I\'m a bit of an amateur and I don\'t know the proper terms to search f

7条回答
  •  無奈伤痛
    2020-11-29 00:33

    EDIT Added random movement, like DVD idle screen but can bounce anywhere.

    http://jsfiddle.net/ryXBM/2/

    dirR = "+=2";
    dirL = "+=2";
    
    function moveDir() {
     if (Math.random() > 0.95) {
      swapDirL();
     }
     if (Math.random() < 0.05) {
      swapDirR();
     }
    }
    
    function swapDirL() {
        dirL == "+=2" ? dirL = "-=2" : dirL = "+=2"; 
    }
    
    function swapDirR() {
        dirR == "+=2" ? dirR = "-=2" : dirR = "+=2";   
    }
    
    setInterval (function() { $("#d").css("left", dirL); $("#d").css("top", dirR); moveDir(); } , 50)​
    

    CSS

    #d { position: absolute;
     left: 100px;
     top: 100px;
     width: 100px;
     height: 100px;
     background-color: #fce;   
    }​
    

提交回复
热议问题