【发布时间】:2019-03-29 07:43:24
【问题描述】:
我尝试移动一组不同的div,为此我做了一个function 以在空间中进行无限移动。现在我想将不同的div 放在一种网格中对它们进行分类。它有时会运行,但不会停止function,并且当放置每个 div 时,它会继续移动。
我不想(不使用像 Particle.js 这样的库)是让它不断移动,但是当我单击时,它会立即停止 div 并从它们的位置运行到网格,并且在第二次单击时,它会从网格到函数。
这里是 Jquery:
$(document).ready(function(){
function move() {
$('div').each(function(){
var top = $(this).css('top');
var left = $(this).css('left');
var topEnd = $(this).data('top-end');
var leftEnd = $(this).data('left-end');
$(this).animate({
left: leftEnd,
top: topEnd
}, 3000).animate({
left: left,
top: top
}, 3000,move);
}
)}
move();
$('button').click(function(){
$('div').each(function(){
var position = $(this).position();
var gridTop = $(this).data('grid-top');
var gridLeft = $(this).data('grid-left');
var topEnd = $(this).data('top-end');
var leftEnd = $(this).data('left-end');
if(position.top == gridTop ){
$(this).animate({
left: leftEnd,
top: topEnd
}, 2000);
} else {
$(this).animate({
left: gridLeft,
top: gridTop
}, 2000);
}
});
});
});
这里是html:
<button>click moi</button>
<div data-grid-left="10px" data-grid-top="130px" data-left-end="250px" data-top-end="250px" style="background:green;left:-50px;"></div>
<div data-grid-left="130px" data-grid-top="10px" data-left-end="350px" data-top-end="-50px" style="background:red;top:200px;left:-200px;"></div>
<div data-grid-left="130px" data-grid-top="130px" data-left-end="500px" data-top-end="100px" style="background:blue;top:400px;left:-100px;"></div>
【问题讨论】:
-
添加 .stop() 到结尾
-
是的...我刚刚找到它
标签: javascript jquery function jquery-animate each