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

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

    well you'll need to capture the dimensions of the window

    then you'll need to generate random numbers <= the height and width of the screen (minus the width/height of the box)

    give the box an absolute position, and give the box have the generated x,y coordinates

    then set a timer to call this function again.

    :)

    $(document).ready(function() {
        randoBox = {
          width:$("body").width(),
          height:$("body").height(),
          x:0,
          y:0,
          el:null,
          time:1000,
          state:"active",
          init: function(){
            el = $(document.createElement('div'));
            el.attr("style","position:absolute;left:"+this.x+";top:"+this.y+";");
            el.html("DVD")            
            el.height(100);
            el.width(100);
            $("body").append(el);
          },
          move:function(){
            this.y = Math.random()*this.height+1;
            this.x = Math.random()*this.width+1;
            el.attr("style","position:absolute;left:"+this.x+";top:"+this.y+";");            
          },
          run:function(state){
            if (this.state == "active" || state){
              this.move();
              setTimeout(function(){this.run()},this.time);
            }
          }
        }
        randoBox.init();
        randoBox.run(true);
    });
    

提交回复
热议问题