javascript中div的随机位置

javascript中div的随机位置,javascript,jquery,position,positioning,Javascript,Jquery,Position,Positioning,我正在尝试使用javascript使div随机出现在网页的任何位置。一个div出现然后消失,然后另一个div出现在页面的其他地方然后消失,然后另一个div再次出现在页面的另一个随机点然后消失,依此类推。 我不确定如何以像素为单位生成随机单位,或者使用什么技术生成随机位置 我该怎么做?这是我的密码: var currentDivPosition = myDiv.offset(), myDivWidth = myDiv.width(), myDivHeight = myDiv.hei

我正在尝试使用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);
var currentDivPosition=myDiv.offset(),
myDivWidth=myDiv.width(),
myDivHeight=myDiv.height(),
var myDiv=$(''),
最终位置顶部,最终位置左侧;
myDiv.attr({id:'myDivId',class:'myDivClass'});//已经用position:absolute定义了CSS文件。
//重新定位
finalDivPositionTop=currentDivPosition.top+Math.floor(Math.random()*100);
finalDivPositionLeft=currentDivPosition.left+Math.floor(Math.random()*100);
css({//Set div position
顶部:最终位置顶部,
左:最终位置左
});
$('body').append(myDiv);
myDiv.text('我的位置是:'+finalDivPositionTop+','+finalDivPositionLeft');
法代因矿业公司(500);
setTimeout(函数(){
myDiv.淡出(500);
myDiv.remove();
}, 3000);
一些错误:

  • 你完全没能确定潜水艇的位置。否则就不会 工作
  • 我想你需要在数字上添加“px”
  • 这张地图是由字符串组成的
  • 就在jQuery css设置中:

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

    假设您有以下HTML:

    <div id="test">test div</div>
    
    使用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 )
        });
    });
    
    其工作方式是……首先计算
    文档的宽度和高度,然后计算
    div
    宽度和高度,然后从<代码>文档> <代码>宽度和<代码> div 高度从.<代码>文档高度中减去“代码> div/<代码>宽度,并考虑您愿意将<代码> div <代码>放入的像素范围(这样它就不会溢出文档)。如果在
    div
    上有填充和边框,则还需要考虑这些值。计算出范围后,可以通过
    Math.random()
    轻松地将其乘以,并找到
    div
    的随机位置

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

    基本思想概括如下:


    这里有一种方法。我在固定范围内随机改变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(); 
        }); 
    })();
    
    (函数makeDiv(){
    //大小不一
    var divsize=((Math.random()*100)+50).toFixed();
    var color='#'+Math.round(0xffffff*Math.random()).toString(16);
    $newdiv=$('').css({
    “宽度”:divsize+'px',
    “高度”:divsize+'px',
    “背景色”:颜色
    });
    //使位置对大小和文档宽度敏感
    var posx=(Math.random()*($(document.width()-divsize)).toFixed();
    var posy=(Math.random()*($(document.height()-divsize)).toFixed();
    $newdiv.css({
    '位置':'绝对',
    “左”:posx+“px”,
    'top':posy+'px',
    “显示”:“无”
    }).appendTo('body').fadeIn(100).延迟(1000).衰减(500,函数(){
    $(this.remove();
    makeDiv();
    }); 
    })();
    
    编辑:为了好玩,添加了一个随机颜色

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


    示例:

    我通过此代码更改了我们网站的现有代码,您可以在

    
    函数绘图(){
    $(画布).attr('width',width).attr('height',height);
    con.clearRect(0,0,宽度,高度);
    对于(变量i=0;i=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=这个.r*newo;
    g=con.createRadialGradient(t
    
    (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(); 
        }); 
    })();
    
    <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>