如何让 div 在页面上随机移动(使用 jQuery 或 CSS) [英] how to get a div to randomly move around a page (using jQuery or CSS)

查看:143
本文介绍了如何让 div 在页面上随机移动(使用 jQuery 或 CSS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

提前致谢!!!

解决方案

基本前提是生成位置值,使用jquery的animate()函数移动div.下一个位置的计算很简单,你只需要一点数学.这是我刚刚敲的一个非常基本的jsfiddle.它可能会使用延迟计时器,这是一种基于其移动距离等动态计算速度的方法.但它给了你一个我希望的起点.

http://jsfiddle.net/Xw29r/

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

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

<小时>

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

http://jsfiddle.net/bf9nv1q6/

function RandomObjectMover(obj, container) {this.$object = obj;this.$container = 容器;this.container_is_window = 容器 === 窗口;this.pixels_per_second = 250;this.current_position = { x: 0, y: 0 };this.is_running = false;}//以每秒像素为单位设置移动速度.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 };} 别的 {return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };}}RandomObjectMover.prototype._generateNewPosition = function() {//获取容器尺寸减去 div 尺寸var containerSize = this._getContainerDimensions();var availableHeight = containerSize.height - this.$object.clientHeight;var availableWidth = containerSize.width - this.$object.clientHeight;//在空间中随机选择一个位置var y = Math.floor(Math.random() * availableHeight);var x = Math.floor(Math.random() * availableWidth);返回 { 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);返回距离;}RandomObjectMover.prototype._moveOnce = function() {//在页面上选择一个新位置var next = this._generateNewPosition();//我们必须移动多远?var delta = this._calcDelta(this.current_position, next);//此转换的速度,四舍五入为 2DPvar 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)';//保存这个新位置以备下次调用.this.current_position = 下一个;};RandomObjectMover.prototype.start = function() {如果(this.is_running){返回;}//确保我们的对象设置了正确的 cssthis.$object.willChange = '转换';this.$object.pointerEvents = 'auto';this.boundEvent = this._moveOnce.bind(this)//绑定回调以保持移动this.$object.addEventListener('transitionend', this.boundEvent);//开始移动this._moveOnce();this.is_running = true;}RandomObjectMover.prototype.stop = function() {如果(!this.is_running){返回;}this.$object.removeEventListener('transitionend', this.boundEvent);this.is_running = false;}//初始化var x = new RandomObjectMover(document.getElementById('a'), window);//工具栏内容document.getElementById('start').addEventListener('click', function(){x.开始();});document.getElementById('stop').addEventListener('click', function(){x.停止();});document.getElementById('speed').addEventListener('keyup', function(){如果 (parseInt(this.value) > 3000 ) {alert('别傻了,别傻了');this.value = 250;}x.setSpeed(parseInt(this.value));});//启动它x.start();

div#toolbar {位置:固定;背景:#20262F;宽度:100%;文字对齐:居中;填充:10px}div#a {宽度:50px;高度:50px;背景颜色:红色;位置:绝对;}

<button id="开始">开始</button><button id="stop">停止</button><input type="number" value="250" id="speed"/>

<div id='a'></div>

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.

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.

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.

Thanks in advance!!!

解决方案

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.

http://jsfiddle.net/Xw29r/

Updated example code with speed modifier:

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.

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>

这篇关于如何让 div 在页面上随机移动(使用 jQuery 或 CSS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆