如何让div在页面上随机移动(使用jQuery或CSS)

Eph*_*aim 21 css jquery animation

我一直在做一些谷歌搜索来找到答案,但我没有运气.这可能是因为我有点像业余爱好者而且我不知道要搜索的正确术语,但也许有人可以引导我朝着正确的方向前进或者帮助我.

无论如何,我正在寻找一种方法让一个div随机,平稳地移动页面.会有一个背景颜色,然后我想看似随机的这个图像,无限地在页面周围移动.就像DVD播放机主屏幕的背景一样,"DVD"只是漂浮在周围.

div的起点无关紧要,终点也不重要.它只需要在用户在该页面上的持续时间内随机移动页面.

我有很好的HTML和CSS技能,非常基本的JS技能,以及一些实现jQuery的经验.理想情况下,我想要一些我可以自己实现的东西.

提前致谢!!!

Lee*_*Lee 39

基本前提是生成位置值,并使用jquery的animate()函数来移动div.下一个位置的计算很简单,你只需要一点数学.这是一个非常基本的jsfiddle我刚刚被击倒.它可以做一个延迟计时器,一个动态计算速度,根据它移动得多远等但它给你一个我希望的起点.

http://jsfiddle.net/Xw29r/

使用速度修饰符更新了示例代码:

http://jsfiddle.net/Xw29r/15/


Ror*_*san 6

试试这个:

function moveDiv() {
    var $span = $("#random");

    $span.fadeOut(1000, function() {
        var maxLeft = $(window).width() - $span.width();
        var maxTop = $(window).height() - $span.height();
        var leftPos = Math.floor(Math.random() * (maxLeft + 1))
        var topPos = Math.floor(Math.random() * (maxTop + 1))

        $span.css({ left: leftPos, top: topPos }).fadeIn(1000);
    });
};

moveDiv();
setInterval(moveDiv, 5000);
Run Code Online (Sandbox Code Playgroud)

示例小提琴


RGB*_*RGB 5

那么你需要捕捉到的尺寸 window

那么你需要generate random numbers <=heightwidthscreen(减去width/ heightbox)

给盒子一个absolute位置,然后给盒子生成x,y coordinates

然后设置一个计时器this function再次调用.

:)

$(document).ready(function() {
    randoBox = {
      width:$("body").width(),
      height:$("body").height(),
      x:0,
      y:0,
      el:null,
      time:1000,
      state:"active",
      init: function(){
        el = $(document.createElement('div'));
        el.attr("style","position:absolute;left:"+this.x+";top:"+this.y+";");
        el.html("DVD")            
        el.height(100);
        el.width(100);
        $("body").append(el);
      },
      move:function(){
        this.y = Math.random()*this.height+1;
        this.x = Math.random()*this.width+1;
        el.attr("style","position:absolute;left:"+this.x+";top:"+this.y+";");            
      },
      run:function(state){
        if (this.state == "active" || state){
          this.move();
          setTimeout(function(){this.run()},this.time);
        }
      }
    }
    randoBox.init();
    randoBox.run(true);
});
Run Code Online (Sandbox Code Playgroud)