javascript中div的随机位置 [英] random position of divs in javascript
问题描述
我正在尝试使用javascript在网页上的任意位置随机显示Div。因此div出现然后消失,然后另一个div出现在页面上的其他地方然后消失,然后另一个div再次出现在页面上的另一个随机点然后消失,依此类推。
我不确定如何生成像素的随机单位或用什么技术来生成随机位置。
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);
推荐答案
这是一种方法。我在固定范围内随机改变div的大小,然后设置位置,使对象始终位于当前窗口边界内。
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();
});
})();
编辑:为了好玩,添加了随机颜色。
For fun, added a random color.
编辑:添加 .remove()
所以我们不会用旧div污染页面。
Added .remove()
so we don't pollute the page with old divs.
示例: http://jsfiddle.net/redler/QcUPk/8/
这篇关于javascript中div的随机位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!