Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - random position of divs in javascript

I'm trying to make Divs to appear randomly anywhere on a webpage with javascript. So a div appears then disappears, then another div appears somewhere else on the page then disappears, then another div appears again in another random spot on the page then disappears, and so on. I'm not sure on how to generate random units in pixels or what technique to use to generate random positions.

How do I do that? Here's my code:

var currentDivPosition = myDiv.offset(),
    myDivWidth = myDiv.width(),
    myDivHeight = myDiv.height(),
            var myDiv = $('<div>'),
    finalDivPositionTop, finalDivPositionLeft;

myDiv.attr({ id: 'myDivId', class: 'myDivClass' }); // already defined with position: absolute is CSS file.

// Set new position     
finalDivPositionTop = currentDivPosition.top + Math.floor( Math.random() * 100 );
finalDivPositionLeft = currentDivPosition.left + Math.floor( Math.random() * 100 );

myDiv.css({ // Set div position
  top: finalDivPositionTop,
  left: finalDivPositionLeft
});

$('body').append(myDiv);

myDiv.text('My position is: ' + finalDivPositionTop + ', ' + finalDivPositionLeft); 

myDiv.fadeIn(500);

setTimeout(function(){

  myDiv.fadeOut(500);

  myDiv.remove();       

}, 3000);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's one way to do it. I'm randomly varying the size of the div within a fixed range, then setting the position so the object is always placed within the current window boundaries.

(function makeDiv(){
    // vary size for fun
    var divsize = ((Math.random()*100) + 50).toFixed();
    var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
    $newdiv = $('<div/>').css({
        'width':divsize+'px',
        'height':divsize+'px',
        'background-color': color
    });

    // make position sensitive to size and document's width
    var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
    var posy = (Math.random() * ($(document).height() - divsize)).toFixed();

    $newdiv.css({
        'position':'absolute',
        'left':posx+'px',
        'top':posy+'px',
        'display':'none'
    }).appendTo( 'body' ).fadeIn(100).delay(1000).fadeOut(500, function(){
      $(this).remove();
      makeDiv(); 
    }); 
})();

Edit: For fun, added a random color.

Edit: Added .remove() so we don't pollute the page with old divs.

Example: http://jsfiddle.net/redler/QcUPk/8/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...