小编典典

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

css

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

无论如何,我正在寻找一种使div随机,平滑地在页面上移动的方法。会有背景色,然后我想随机地在页面上无限移动此图像。就像DVD播放器主屏幕的背景一样,“
DVD”只是在上面浮动。

div的起点并不重要,终点也不重要。它只需要在用户停留在页面上的持续时间内在页面上随机移动。

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

提前致谢!!!


阅读 1311

收藏
2020-05-16

共1个答案

小编典典

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


由于某种原因,这仍然引起了人们的注意,因此这是一个更新的答案,该答案使用CSS过渡应该会更加流畅。

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>
2020-05-16