首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何让div在页面中随机移动(使用jQuery或CSS)

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

Stack Overflow用户
提问于 2012-04-30 23:07:48
回答 4查看 93.6K关注 0票数 28

我已经做了一些谷歌搜索,以找到这个问题的答案,但我一直没有运气。这可能是因为我是一个业余爱好者,我不知道该用什么词来搜索,但也许这里的某个人可以给我指引正确的方向或帮助我解决问题。

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

div的起始点并不重要,结束点也不重要。它只需要在用户停留的时间内在页面上随机移动即可。

我有不错的超文本标记语言和CSS技能,非常基础的JS技能,以及一些实现jQuery的经验。理想情况下,我想要一些可以自己实现的东西。

提前感谢!

EN

回答 4

Stack Overflow用户

发布于 2012-04-30 23:13:45

那么,您需要捕获window的尺寸

然后你需要generate random numbers <= heightwidth of screen (减去boxwidth/height )

给长方体一个absolute位置,并给长方体生成的xy coordinates

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

:)

代码语言:javascript
复制
$(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);
});
票数 6
EN

Stack Overflow用户

发布于 2012-04-30 23:13:05

您可以使用jQuery SlideMath.random(),生成一个随机数作为移动距离,另一个随机数根据移动的方向进行决策。

票数 1
EN

Stack Overflow用户

发布于 2012-04-30 23:14:34

您需要指定动画的边框- topleft属性的最大值是多少……在此之后,您只需要一次又一次地调用.animate()函数……

像这样的东西应该行得通-

代码语言:javascript
复制
var maxLeft = _left_border - $('#selectedElement').width(); // counter intuitively this is actually the right border
var maxTop = _top_border  - $('#selectedElement').height();
var animationDurration = _duration;

function randomAnimation(){
  var randomLeft = Math.floor(Math.random()*maxLeft);
  var randomTop = Math.floor(Math.random()*maxTop);

  $('#selectedElement').animate({
     left: randomLeft,
     top: randomTop
   }, animationDurration, function() {
     randomAnimation();
   });
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10385950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档