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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10385950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:13:33  来源:igfitidea点击:

how to get a div to randomly move around a page (using jQuery or CSS)

jquerycssanimation

提问by Ephraim

I've been doing some Googling to find an answer to this, but I've had no luck. It could be because I'm a bit of an amateur and I don't know the proper terms to search for, but maybe someone here can steer me in the right direction or help me out.

我一直在做一些谷歌搜索来找到这个问题的答案,但我没有运气。可能是因为我有点业余,我不知道要搜索的正确术语,但也许这里有人可以引导我走向正确的方向或帮助我解决问题。

Anyway, I'm looking for a way to get a div to randomly, smoothly move around a page. There will be a background color, then this image which I want to seemingly randomly, infinitely move around the page. Much like the background of a DVD player's home screen where "DVD" is just floating around.

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

Starting point of the div doesn't matter, nor does the ending point. It just needs to randomly move around the page for the duration a user is on that page.

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

I've got decent HTML and CSS skills, very basic JS skills, and some experience implementing jQuery. Ideally, I'd like something which I can implement myself.

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

Thanks in advance!!!

提前致谢!!!

回答by Lee

The basic premise is to generate positional values, and use jquery's animate() function to move the div. The calculation of the next position is simple, you just need a bit of math. Here's a very basic jsfiddle i just knocked up. It could do with possibly a delay timer, a dynamically calculating speed based on how far its got too move e.c.t. But it gives you a start point i hope.

基本前提是生成位置值,使用jquery的animate()函数移动div。下一个位置的计算很简单,你只需要一点数学。这是我刚刚敲的一个非常基本的jsfiddle。它可能与延迟计时器有关,它可以根据其移动的距离等动态计算速度,但我希望它为您提供了一个起点。

http://jsfiddle.net/Xw29r/

http://jsfiddle.net/Xw29r/

Updated example code with speed modifier:

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

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

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



For some reason this is still getting some attention, so here's an updated answer that uses CSS transitions which should be much smoother.

出于某种原因,这仍然引起了一些关注,所以这里有一个更新的答案,它使用了应该更平滑的 CSS 过渡。

http://jsfiddle.net/bf9nv1q6/

http://jsfiddle.net/bf9nv1q6/

function RandomObjectMover(obj, container) {
 this.$object = obj;
  this.$container = container;
  this.container_is_window = container === window;
  this.pixels_per_second = 250;
  this.current_position = { x: 0, y: 0 };
  this.is_running = false;
}

// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
 this.pixels_per_second = pxPerSec;
}

RandomObjectMover.prototype._getContainerDimensions = function() {
   if (this.$container === window) {
       return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
   } else {
       return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
   }
}

RandomObjectMover.prototype._generateNewPosition = function() {

 // Get container dimensions minus div size
  var containerSize = this._getContainerDimensions();
 var availableHeight = containerSize.height - this.$object.clientHeight;
  var availableWidth = containerSize.width - this.$object.clientHeight;
    
  // Pick a random place in the space
  var y = Math.floor(Math.random() * availableHeight);
  var x = Math.floor(Math.random() * availableWidth);
    
  return { x: x, y: y };    
}

RandomObjectMover.prototype._calcDelta = function(a, b) {
 var dx   = a.x - b.x;         
  var dy   = a.y - b.y;         
  var dist = Math.sqrt( dx*dx + dy*dy ); 
  return dist;
}

RandomObjectMover.prototype._moveOnce = function() {
  // Pick a new spot on the page
    var next = this._generateNewPosition();
    
    // How far do we have to move?
    var delta = this._calcDelta(this.current_position, next);
    
  // Speed of this transition, rounded to 2DP
  var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
    
    //console.log(this.current_position, next, delta, speed);
          
    this.$object.style.transition='transform '+speed+'s linear';
    this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
    
    // Save this new position ready for the next call.
    this.current_position = next;
  
};

RandomObjectMover.prototype.start = function() {

 if (this.is_running) {
   return;
  }

 // Make sure our object has the right css set
  this.$object.willChange = 'transform';
  this.$object.pointerEvents = 'auto';
 
  this.boundEvent = this._moveOnce.bind(this)
  
  // Bind callback to keep things moving
  this.$object.addEventListener('transitionend', this.boundEvent);
  
  // Start it moving
  this._moveOnce();
  
  this.is_running = true;
}

RandomObjectMover.prototype.stop = function() {

 if (!this.is_running) {
   return;
  }
  
  this.$object.removeEventListener('transitionend', this.boundEvent);
  
 this.is_running = false;
}


// Init it
var x = new RandomObjectMover(document.getElementById('a'), window);


// Toolbar stuff
document.getElementById('start').addEventListener('click', function(){
 x.start();
});
document.getElementById('stop').addEventListener('click', function(){
 x.stop();
});
document.getElementById('speed').addEventListener('keyup', function(){
  if (parseInt(this.value) > 3000 ) {
   alert('Don\'t be stupid, stupid');
    this.value = 250;
  }
 x.setSpeed(parseInt(this.value));
});


// Start it off

x.start();
div#toolbar {
  position:fixed;
  background:#20262F;
  width:100%;
  text-align:center;
  padding: 10px
}
div#a {
width: 50px;
height:50px;
background-color:red;
position:absolute;
}
<div id="toolbar">
<button id="start">Start</button>
<button id="stop">Stop</button>
<input type="number" value="250" id="speed" />
</div>
<div id='a'></div>

回答by Rory McCrossan

Try this:

尝试这个:

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

Example fiddle

示例小提琴

回答by RGB

well you'll need to capture the dimensions of the window

那么你需要捕获的尺寸 window

then you'll need to generate random numbers<=the heightand widthof the screen(minus the width/heightof the box)

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

give the box an absoluteposition, and give the box have the generated x,ycoordinates

给盒子一个absolute位置,给盒子生成一个xycoordinates

then set a timer to call this functionagain.

然后设置一个定时器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);
});

回答by Heitor Chang

EDITAdded random movement, like DVD idle screen but can bounce anywhere.

编辑添加随机运动,如 DVD 空闲屏幕,但可以在任何地方弹跳。

http://jsfiddle.net/ryXBM/2/

http://jsfiddle.net/ryXBM/2/

dirR = "+=2";
dirL = "+=2";

function moveDir() {
 if (Math.random() > 0.95) {
  swapDirL();
 }
 if (Math.random() < 0.05) {
  swapDirR();
 }
}

function swapDirL() {
    dirL == "+=2" ? dirL = "-=2" : dirL = "+=2"; 
}

function swapDirR() {
    dirR == "+=2" ? dirR = "-=2" : dirR = "+=2";   
}

setInterval (function() { $("#d").css("left", dirL); $("#d").css("top", dirR); moveDir(); } , 50)?

CSS

CSS

#d { position: absolute;
 left: 100px;
 top: 100px;
 width: 100px;
 height: 100px;
 background-color: #fce;   
}?

回答by Rupa Das

<html>
    <head>
        <link rel="stylesheet" href="sample1.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                    $('.btn').mouseover(function(){
                        $(this).css({
                            left:(Math.random()*$(window).width()-20),
                            top:(Math.random()*$(window).height()-20),      
                        });
                    });              
            });
        </script>
    </head> 
    <body>
        <div class="btn" style="position: absolute">button</div>
    </body>
</html> 

回答by Lix

You'll want to specify the borders of the animation - what is the maximum values for the topand leftattributes... After that all you need is the .animate()function to be called again and again...

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

Something like this should work -

这样的事情应该工作 -

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

回答by Mitch Satchwell

You could use jQuery Slideand Math.random(), generating one random number to use as the distance to move and another random number to base your decision on which direction to move in.

您可以使用jQuery SlideMath.random(),生成一个随机数用作移动距离,生成另一个随机数来决定移动的方向。