javascript中div的随机位置

发布于 2024-10-13 18:40:12 字数 1010 浏览 2 评论 0原文

我正在尝试使用 javascript 使 Div 随机出现在网页上的任何位置。因此,一个 div 出现然后消失,然后另一个 div 出现在页面上的其他位置然后消失,然后另一个 div 再次出现在页面上的另一个随机位置然后消失,依此类推。 我不确定如何生成像素随机单位或使用什么技术生成随机位置。

我该怎么做?这是我的代码:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

郁金香雨 2024-10-20 18:40:12

这是一种方法。我在固定范围内随机改变 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(); 
    }); 
})();

编辑:为了好玩,添加了随机颜色。

编辑:添加了 .remove() 这样我们就不会用旧的 div 污染页面。

示例: http://jsfiddle.net/redler/QcUPk/8/

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/

坠似风落 2024-10-20 18:40:12

假设您有这个 HTML:

<div id="test">test div</div>

和这个 CSS:

#test {
    position:absolute;
    width:100px;
    height:70px;
    background-color:#d2fcd9;
}

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

其工作方式是...首先计算 document 宽度和高度,然后计算 div 宽度和高度,然后从 document 宽度中减去 div 宽度和 div 距离 document 高度的高度,并考虑您愿意放入 div 的像素范围(因此它不会溢出文档)。如果 div 上有内边距和边框,则还需要考虑这些值。一旦确定了范围,您就可以通过 Math.random() 轻松地乘以该范围,并找到 div 的随机位置。

所以再一次:首先找到容器的尺寸,然后找到元素的尺寸,然后从容器尺寸中减去元素尺寸,然后对该值使用 Math.random()

基本思想封装在这里:

http://jsfiddle.net/5mvKE/

Let's say you have this HTML:

<div id="test">test div</div>

And this 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:

$('#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.

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.

The basic idea is encapsulated here:

http://jsfiddle.net/5mvKE/

谜兔 2024-10-20 18:40:12

一些错误:

  1. 您错过了对 div 的绝对定位。否则不会
    工作。
  2. 我认为您需要在数字中添加“px”。
  3. 该地图由字符串组成

,就在您的 jQuery css 设置中:

myDiv.css({
    'position' : 'absolute',
    'top' : finalDivPositionTop + 'px',
    'left' : finalDivPositionLeft + 'px'
});

Some bugs:

  1. You missed to position the div absolutely. Otherwise it will not
    work.
  2. I think you need to ad 'px' to the numbers.
  3. The map is made of strings

Right in your jQuery css setup:

myDiv.css({
    'position' : 'absolute',
    'top' : finalDivPositionTop + 'px',
    'left' : finalDivPositionLeft + 'px'
});
蓝颜夕 2024-10-20 18:40:12

我通过这个为我们的网站更改了现有代码,您可以在 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>

I changed an existant code by this one for our website, you can see it on 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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文