我在页面上有多个图像,这些图像是使用PHP动态加载的。我希望它们都在整个屏幕上朝不同的方向移动。
到目前为止,图像在随机方向上移动,但都在同一位置。
PHP:
<?php foreach($logos as $logo) {
$logoName = $logo['Logo_Link']; ?>
<img class="imglogo" src="images/<?php echo $logoName ?>" />
<?php } ?>
JS:
$(document).ready(function() {
animateDiv();
});
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 = $('.imglogo');
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.imglogo').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;
}
答案 0 :(得分:0)
我刚刚在animateDiv
函数中进行了循环
animateDiv();
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 = $('.imglogo');
for(let i=0; i<$target.length; i++){
var newq = makeNewPosition($($target[0]).parent());
var oldq = $($target[0]).offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$($('.imglogo')[i]).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;
}
.imglogo{
width: 40px;
height: 40px;
background-color: blue;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>
<div class="imglogo"></div>