how to get a div to randomly move around a page (u

2019-01-06 11:00发布

问题:

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 for, but maybe someone here can steer me in the right direction or help me out.

Anyway, I'm looking for a way to get a div to randomly, smoothly move around a page. There will be a background color, then this image which I want to seemingly randomly, infinitely move around the page. Much like the background of a DVD player's home screen where "DVD" is just floating around.

Starting point of the div doesn't matter, nor does the ending point. It just needs to randomly move around the page for the duration a user is on that page.

I've got decent HTML and CSS skills, very basic JS skills, and some experience implementing jQuery. Ideally, I'd like something which I can implement myself.

Thanks in advance!!!

回答1:

The basic premise is to generate positional values, and use jquery's animate() function to move the div. The calculation of the next position is simple, you just need a bit of math. Here's a very basic jsfiddle i just knocked up. It could do with possibly a delay timer, a dynamically calculating speed based on how far its got too move e.c.t. But it gives you a start point i hope.

http://jsfiddle.net/Xw29r/

Updated example code with speed modifier:

http://jsfiddle.net/Xw29r/15/



回答2:

Try this:

function moveDiv() {
    var $span = $("#random");

    $span.fadeOut(1000, function() {
        var maxLeft = $(window).width() - $span.width();
        var maxTop = $(window).height() - $span.height();
        var leftPos = Math.floor(Math.random() * (maxLeft + 1))
        var topPos = Math.floor(Math.random() * (maxTop + 1))

        $span.css({ left: leftPos, top: topPos }).fadeIn(1000);
    });
};

moveDiv();
setInterval(moveDiv, 5000);

Example fiddle



回答3:

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);
});


回答4:

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;   
}​


回答5:

You could use jQuery Slide and Math.random(), generating one random number to use as the distance to move and another random number to base your decision on which direction to move in.



回答6:

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();
   });
}


回答7:

<html>
    <head>
        <link rel="stylesheet" href="sample1.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                    $('.btn').mouseover(function(){
                        $(this).css({
                            left:(Math.random()*$(window).width()-20),
                            top:(Math.random()*$(window).height()-20),      
                        });
                    });              
            });
        </script>
    </head> 
    <body>
        <div class="btn" style="position: absolute">button</div>
    </body>
</html>