我有这个javascript代码,可以使div在网页上随机移动,但我不明白如何使它不连续流动,就像用户单击然后它移动然后停在那里以及每当它单击时它再次移动到另一个随机位置,5次后它显示一条消息并消失。我不知道如何使这个动画不像流动,而是像从树上落下的叶子。
这是 jsfiddle :JSFIDDLE
下面是 JavaScript 代码:
$(document).ready(function(){
animateDiv();
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest/speedModifier);
return speed;
}
最佳答案
我会使用 CSS3 过渡
,它们具有硬件加速,这意味着动画更流畅:
$(document).ready(function(){
var counter = 0;
$('.a').click( function () {
if ( ++counter < 5 ) {
var pos = makeNewPosition();
this.style.left = pos[1] +'px';
this.style.top = pos[0] +'px';
}
else if ( counter = 5 ) {
this.style.display = 'none';
alert( 'Your message' );
}
});
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
div.a {
width : 50px;
height: 50px;
background-color: red;
position: fixed;
left : 0px;
top : 0px;
-webkit-transition: left 2s, top 2s;
-moz-transition: left 2s, top 2s;
-o-transition: left 2s, top 2s;
transition: left 2s, top 2s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='a'></div>
关于javascript - 随机可点击的 div 在网页中移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29554361/