模拟 DOM 元素的累积

Simulate accumulation of DOM elements

本文关键字:元素 DOM 模拟      更新时间:2023-09-26

我正在对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;
}

这是小提琴:小提琴

还有一个更漂亮的,使用jQuery UI,以防这是你要找的:小提琴