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

前端 未结 7 875
旧时难觅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:40

    You'll want to specify the borders of the animation - what is the maximum values for the top and left attributes... After that all you need is the .animate() function to be called again and again...

    Something like this should work -

    var maxLeft = _left_border - $('#selectedElement').width(); // counter intuitively this is actually the right border
    var maxTop = _top_border  - $('#selectedElement').height();
    var animationDurration = _duration;
    
    function randomAnimation(){
      var randomLeft = Math.floor(Math.random()*maxLeft);
      var randomTop = Math.floor(Math.random()*maxTop);
    
      $('#selectedElement').animate({
         left: randomLeft,
         top: randomTop
       }, animationDurration, function() {
         randomAnimation();
       });
    }
    
    0 讨论(0)
提交回复
热议问题