我正在尝试创建 div 的随机移动(成功),并与随机不透明度更改(部分成功)相关联。我通过将两个单独的脚本混合在一起,将以下内容组合在一起。
不透明度仅在 div 的每次移动后发生变化。最终,我想让不透明度独立于运动而工作。任何帮助,将不胜感激!
我在这里的 jsFiddle中有它,或者:
HTML:
<div id="container">
<div class="a"></div>
</div>
CSS:
div#container {height:500px;width:100%;}
div.a {
width: 284px;
height:129px;
background:url(http://www.themasterbetas.com/wp-content/uploads/2013/08/aliens.png);
position:fixed;
}
jQuery:
$(document).ready(function() {
animateDiv();
runIt();
});
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
$container = ($container || $(window));
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var $target = $('.a');
var newq = makeNewPosition($target.parent());
var oldq = $target.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;
}
function runIt() {
var $fading = $('.a');
$fading.fadeTo("fast", Math.random(), runIt);
}