【问题标题】:Replace only differences in DOM仅替换 DOM 中的差异
【发布时间】:2013-02-01 17:44:17
【问题描述】:

我有一个数据模型和许多将视图渲染到 DOM 的渲染方法。目前,当数据发生变化时,我会使用相应的方法重新渲染 DOM。它工作得很好。现在我想要的是我不重新渲染整个 DOM,而是将当前 DOM 与渲染方法的输出进行比较,只替换差异!为什么我需要那个?我希望 css-transitions 使动画平滑,所以我不能替换整个 DOM,只能替换差异。

我迫不及待地等待您的意见,以便在不检查具体更改的情况下完成这项工作。我想把它抽象化。

【问题讨论】:

标签: jquery dom animation rendering transition


【解决方案1】:

好的,我做得很辛苦...如果有人有更优雅的解决方案,如果他分享我会很高兴! :-)

function applyChanges(source, destination) {

    var srcAttributes = source[0].attributes;
    var dstAttributes = destination[0].attributes;

    for (var i = 0; i < dstAttributes.length; i++) {
        if (typeof srcAttributes[dstAttributes[i].nodeName] === "undefined") {
            destination.removeAttr(dstAttributes[i].nodeName);
        }
    }

    for (var i = 0; i < srcAttributes.length; i++) {
        if (typeof dstAttributes[srcAttributes[i].nodeName] === "undefined" || srcAttributes[srcAttributes[i].nodeName].nodeValue != dstAttributes[srcAttributes[i].nodeName].nodeValue) {
            $(destination).attr(srcAttributes[i].nodeName, srcAttributes[i].nodeValue);
        }
    }

    if (destination[0].children.length != source[0].children.length) {
        destination.html(source.html());
        return;
    }

    for (var i = 0; i < source[0].children.length; i++) {
        var srcChild = source[0].children[i];
        var dstChild = destination[0].children[i];

        if ($(srcChild).outerHtml() != $(dstChild).outerHtml()) {
            applyChanges($(srcChild), $(dstChild));
        }
    }

    if (destination.html() != source.html()) {
        destination.html(source.html());
    }
}

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2011-02-01
    • 2013-04-17
    相关资源
    最近更新 更多