gpt4 book ai didi

javascript - 模拟 DOM 元素的累积

转载 作者:行者123 更新时间:2023-12-03 11:17:46 24 4
gpt4 key购买 nike

我正在为 div 容器 holder 中的几个图像元素子元素设置动画...它们会逐渐从屏幕的顶部落到底部

我想模拟堆积...意思是,如果一个图像与另一个图像相交,它将躺在它上面并停止移动(图片雪花飘落并堆积)

我想到的方法是迭代每个子图像并为其位置设置动画...然后循环遍历每个同级图像并检查是否存在交叉点...但是当然这个双循环提供了糟糕的性能...有什么想法吗?

function update () {
var myInterval = null;
clearInterval(myInterval);
myInterval = setInterval(function() {
$("#holder > img").each(function() {
$(this).css({top: $(this).position().top+=3});

var $el = $(this); //bind context
$el.siblings().each(function() {
if ($el.position().top >= $(this).position().top) {
log("INTERSECT");
}
});
});
}, 10);
}

最佳答案

需要考虑两件事:

  1. 看来您正在尝试自己一步一步制作动画。使用 jQuery 的 . animate()相反。

  2. 当布局引擎可以为您执行此操作时,无需检查交叉点。只需将图像放在需要的位置,但以最初不可见的方式放置即可。例如,position:relative;bottom: someVeryBigNumber;。然后将它们动画到最终位置。

<div id="container">
<div id="droppableWrapper">
<div class="droppable"></div>
<div class="droppable"></div>
<div class="droppable"></div>
<div class="droppable"></div>
<div class="droppable"></div>
</div>
</div>
#container {
position: relative;
}

#droppableWrapper {
position: absolute;
bottom: 0px;
}

.droppable {
position: relative;
bottom: 1000px; /* Enough to be out of the screen */
}
var stack = new Array();

$(".droppable").each(function(){
// Note that the order of the stack
// is the inverse of the visual "stack" effect.
stack.push(new Droppable($(this)));
});

startDropping();

function startDropping(){
dropNext();
}

function dropNext(){
var droppable = stack.pop();
if(droppable){
droppable.drop().done(dropNext);
}
}

function Droppable(domElem) {
function drop(){
return domElem.animate({
bottom :"0px"
},{
duration: 1000
}).promise();
}
this.drop = drop;
}

这是一个 fiddle : fiddle

还有一个更高级的,使用 jQuery UI,如果这就是您正在寻找的: fiddle

关于javascript - 模拟 DOM 元素的累积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27260469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com