我试图让一个 div 在随机移动时逐渐出现和消失,但它不起作用,它没有移动,是固定的。这是我有问题的代码的示例。div 只会消失和出现。请帮忙。
CSS
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}
JAVASCRIPT
var opacidad = [0.0, 1.0];
var visibilidad = ['hidden', 'visible'];
$(document).ready(function () {
animateDiv();
});
function makeNewPosition() {
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);
movimiento(newq, speed);
};
function movimiento(newq, speed) {
//alert(newq)
var newq = Math.floor(parseFloat(newq) / 2);
//alert(newq)
$('.a').animate({
top: newq[0],
left: newq[1],
opacity: opacidad[0]
}, speed).css({
visibility: visibilidad[0]
})
var newq = Math.floor(parseFloat(newq) * 2);
//alert(newq)
$('.a').animate({
top: newq[0],
left: newq[1],
opacity: opacidad[1]
}, speed)
.css({
visibility: visibilidad[1]
}, 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;
}