我已经做了一些谷歌搜索,以找到这个问题的答案,但我一直没有运气。这可能是因为我是一个业余爱好者,我不知道该用什么词来搜索,但也许这里的某个人可以给我指引正确的方向或帮助我解决问题。
无论如何,我正在寻找一种让div在页面上随机、平滑地移动的方法。会有一个背景颜色,然后这个图像,我想要的似乎是随机的,无限地在页面上移动。就像DVD播放器的主屏幕的背景一样,"DVD“只是漂浮在周围。
div的起始点并不重要,结束点也不重要。它只需要在用户停留的时间内在页面上随机移动即可。
我有不错的超文本标记语言和CSS技能,非常基础的JS技能,以及一些实现jQuery的经验。理想情况下,我想要一些可以自己实现的东西。
提前感谢!
发布于 2012-04-30 23:13:45
那么,您需要捕获window
的尺寸
然后你需要generate random numbers
<=
height
和width
of screen
(减去box
的width
/height
)
给长方体一个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);
});
发布于 2012-04-30 23:13:05
您可以使用jQuery Slide和Math.random(),生成一个随机数作为移动距离,另一个随机数根据移动的方向进行决策。
发布于 2012-04-30 23:14:34
您需要指定动画的边框- top
和left
属性的最大值是多少……在此之后,您只需要一次又一次地调用.animate()
函数……
像这样的东西应该行得通-
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();
});
}
https://stackoverflow.com/questions/10385950
复制相似问题