【问题标题】:Velocity JS and Dynamically Added DOM ElementsVelocity JS 和动态添加的 DOM 元素
【发布时间】:2015-05-22 21:32:41
【问题描述】:

我有两个可以描述我的问题的 CodePens。我正在使用 Velocity 为页面上的 React 渲染元素设置动画。

目标是根据排名在页面上下移动这些“文章”。它们是绝对定位的,我根据rank * height确定页面上的位置。

working example 成功显示所有元素,然后在 setTimeout 2 秒后反转顺序。

non-working example 应该做同样的事情,但它在页面上移动的唯一一个是最终的 DOM 对象 (id=article-5)。

示例之间的唯一区别是working example 在页面上已经渲染了 DOM 元素,而 non-working example 通过 JavaScript 渲染 HTML

var articlesContainer = document.getElementsByClassName('articles')[0];
for (var i = 1; i <= 5; i++) {
  articlesContainer.innerHTML = articlesContainer.innerHTML + '<div id=article-' + i + '></div>';
}

不太确定为什么动态添加 HTML 元素会破坏这一点。值得注意的是,前 4 个未能动画化的元素具有 velocity-animating 类,这意味着 Velocity 至少尝试过动画化对象,但似乎在某个地方失败了。

有什么想法吗?

【问题讨论】:

    标签: javascript animation reactjs velocity.js


    【解决方案1】:

    当您执行articlesContainer.innerHTML = newHTML 时,您将卸载articlesContainer 中的所有节点并安装新节点。因此,Velocity/React 在分离的节点上运行,除了最后一个文章节点,它是唯一没有卸载的节点。请改用document.createElementnode.appendChild

    var articlesContainer = document.getElementsByClassName('articles')[0];
    for (var i = 1; i <= 5; i++) {
      var div = document.createElement('div');
      articlesContainer.appendChild(div);
    }
    

    【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 2014-09-20
    • 2019-05-24
    • 2011-04-22
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多