【问题标题】:random position of divs in javascriptjavascript中div的随机位置
【发布时间】:2011-06-15 08:49:57
【问题描述】:

我正在尝试使用 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);

【问题讨论】:

  • 你是如何定义myDiv的?
  • @Lance: 像这样,var myDiv = $('div');
  • 您要定位的区域应该是 X: 0 to max(x) - divwidth,任何其他方式都会不时将其定位在可视区域之外,或者显示偏向右侧屏幕。

标签: javascript jquery position positioning


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 非常感谢这是我想要的。但是为什么,当我删除$newdiv = $('&lt;div/&gt;').css... 时,代码不再起作用了?
    • $newdiv 是一个指向新创建的未附加 div 的变量。如果你删除它,就没有新的 div 可以定位和添加到 DOM。如果你想合并东西,你可以把两个.css()方法放在一个块中(在位置计算下面)。
    • 谢谢Ken,我知道为什么它不起作用了,因为div里面没有内容,即文本,...等等。所以它不会出现。但它现在可以工作了
    【解决方案3】:

    假设你有这个 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/

    【讨论】:

    • 您好,如何更改 div 内的文本,同时让 div 自动随机化而不是单击
    【解决方案4】:

    一些错误:

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

    就在您的 jQuery css 设置中:

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

    【讨论】:

    • 地图也可以是不带字符串的单词。
    猜你喜欢
    • 1970-01-01
    • 2018-03-31
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多