Javascript javascript中div的随机位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4796743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
random position of divs in javascript
提问by Shaoz
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.
我正在尝试使用 javascript 使 Div 随机出现在网页上的任何位置。所以一个div出现然后消失,然后另一个div出现在页面上的其他地方然后消失,然后另一个div再次出现在页面上的另一个随机位置然后消失,依此类推。我不确定如何以像素为单位生成随机单位或使用什么技术来生成随机位置。
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);
回答by Ken Redler
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.
这是一种方法。我在固定范围内随机改变 div 的大小,然后设置位置,以便对象始终放置在当前窗口边界内。
(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.
编辑:添加.remove()
以便我们不会用旧的 div 污染页面。
Example: http://jsfiddle.net/redler/QcUPk/8/
回答by treeface
Let's say you have this HTML:
假设你有这个 HTML:
<div id="test">test div</div>
And this CSS:
这个CSS:
#test {
position:absolute;
width:100px;
height:70px;
background-color:#d2fcd9;
}
Using jQuery, if you use this script, whenever you click the div, it will position itself randomly in the document:
使用jQuery,如果你使用这个脚本,每当你点击div时,它会在文档中随机定位:
$('#test').click(function() {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax )
});
});
The way this works is...first you calculate the document
width and height, then you calculate the div
width and height, and then you subtract the div
width from the document
width and the div
height from the document
height and consider that the pixel range you're willing to put the div
in (so it doesn't overflow out of the document). If you have padding and border on the div
, you'll need to account for those values too. Once you've figured out the range, you can easily multiple that by Math.random()
and find the random position of your div
.
它的工作方式是......首先计算document
宽度和高度,然后计算div
宽度和高度,然后div
从document
宽度中减去宽度,从div
高度中减去document
高度,并考虑您愿意的像素范围放入div
(这样它就不会从文档中溢出)。如果在 上有填充和边框,则div
还需要考虑这些值。一旦确定了范围,您就可以轻松地乘以它Math.random()
并找到div
.
So once more: first find the dimensions of the container, then find the dimensions of your element, then subtract element dimensions from container dimensions, and THEN use Math.random()
on that value.
所以再次:首先找到容器的尺寸,然后找到元素的尺寸,然后从容器尺寸中减去元素尺寸,然后使用Math.random()
该值。
The basic idea is encapsulated here:
基本思想封装在这里:
回答by sidyll
Some bugs:
一些错误:
- You missed to position the div absolutely. Otherwise it will not work.
- I think you need to ad 'px' to the numbers.
- The map is made of strings
- 你错过了绝对定位 div。否则它将无法工作。
- 我认为您需要在数字上添加“px”。
- 地图由字符串组成
Right in your jQuery css setup:
就在您的 jQuery css 设置中:
myDiv.css({
'position' : 'absolute',
'top' : finalDivPositionTop + 'px',
'left' : finalDivPositionLeft + 'px'
});
回答by AngeCorse
I changed an existant code by this one for our website, you can see it on tweefox.nc
我通过这个为我们的网站更改了现有代码,您可以在tweefox.nc上看到它
<script>
function draw() {
$(canvas).attr('width', WIDTH).attr('height',HEIGHT);
con.clearRect(0,0,WIDTH,HEIGHT);
for(var i = 0; i < pxs.length; i++) {
pxs[i].fade();
pxs[i].move();
pxs[i].draw();
}
}
function Circle() {
this.s = {ttl:8000, xmax:10, ymax:4, rmax:10, rt:1, xdef:950, ydef:425, xdrift:4, ydrift: 4, random:true, blink:true};
this.reset = function() {
this.x = (this.s.random ? WIDTH*Math.random() : this.s.xdef);
this.y = (this.s.random ? HEIGHT*Math.random() : this.s.ydef);
this.r = ((this.s.rmax-1)*Math.random()) + 1;
this.dx = (Math.random()*this.s.xmax) * (Math.random() < .5 ? -1 : 1);
this.dy = (Math.random()*this.s.ymax) * (Math.random() < .5 ? -1 : 1);
this.hl = (this.s.ttl/rint)*(this.r/this.s.rmax);
this.rt = Math.random()*this.hl;
this.s.rt = Math.random()+1;
this.stop = Math.random()*.2+.4;
this.s.xdrift *= Math.random() * (Math.random() < .5 ? -1 : 1);
this.s.ydrift *= Math.random() * (Math.random() < .5 ? -1 : 1);
}
this.fade = function() {
this.rt += this.s.rt;
}
this.draw = function() {
if(this.s.blink && (this.rt <= 0 || this.rt >= this.hl)) {
this.s.rt = this.s.rt*-1;
this.dx = (Math.random()*this.s.xmax) * (Math.random() < .5 ? -1 : 1);
this.dy = (Math.random()*this.s.ymax) * (Math.random() < .5 ? -1 : 1);
} else if(this.rt >= this.hl) this.reset();
var newo = 1-(this.rt/this.hl);
con.beginPath();
con.arc(this.x,this.y,this.r,0,Math.PI*2,true);
con.closePath();
var cr = this.r*newo;
g = con.createRadialGradient(this.x,this.y,0,this.x,this.y,(cr <= 0 ? 1 : cr));
g.addColorStop(0.0, 'rgba(255,255,255,'+newo+')');
g.addColorStop(this.stop, 'rgba(255,255,255,'+(newo*.2)+')');
g.addColorStop(1.0, 'rgba(255,255,255,0)');
con.fillStyle = g;
con.fill();
}
this.move = function() {
this.x += (this.rt/this.hl)*this.dx;
this.y += (this.rt/this.hl)*this.dy;
if(this.x > WIDTH || this.x < 0) this.dx *= -1;
if(this.y > HEIGHT || this.y < 0) this.dy *= -1;
}
this.getX = function() { return this.x; }
this.getY = function() { return this.y; }
}
$(document).ready(function(){
// if( /Android|AppleWebKit|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// } else {
if(document.getElementById('pixie')) {
WIDTH = $(window).width();
HEIGHT = $(window).height();
canvas = document.getElementById('pixie');
$(canvas).attr('width', WIDTH).attr('height',HEIGHT);
con = canvas.getContext('2d');
pxs = new Array();
rint = 60;
for(var i = 0; i < 50; i++) {
pxs[i] = new Circle();
pxs[i].reset();
}
setInterval(draw,rint);
}
// }
});
</script>