【问题标题】:animation with node appendChild() html带有节点 appendChild() html 的动画
【发布时间】:2012-12-27 08:04:39
【问题描述】:

我对 Web 开发非常陌生,我正在尝试创建一个网页,该网页将在单击按钮时向下延伸。我找到了this link,里面有这段代码:

HTML:

<ul id="myList"><li>Coffee</li><li>Tea</li></ul>

<p id="demo">Click the button to append an item to the list</p>

<button onclick="myFunction()">Try it</button>

JavaScript:

function myFunction()
{
    var node=document.createElement("LI");
    var textnode=document.createTextNode("Water");
    node.appendChild(textnode);
    document.getElementById("myList").appendChild(node);
}

这将添加信息。我想这样做,以便它动画化,而不仅仅是出现。我该怎么办?

感谢任何帮助或教程。谢谢!

【问题讨论】:

  • 您是在寻找纯 JavaScript 解决方案,还是愿意使用 jQuery?
  • 我可以使用 jQuery,但正如我所说,我对它很陌生,你必须帮助将它整合到代码中,哈哈。

标签: javascript html dom web


【解决方案1】:

您必须阅读一些关于 jQuery 的内容,但这里有一个您想要的内容的描述:jQuery using append with effects

原则是首先创建一个 jQuery 对象,它代表您要附加的元素,确保它具有确保它不会立即可见的样式设置(例如display: none)。

然后将元素附加到页面中(此时由于样式设置,浏览器不会呈现它),最后使用 jQuery 方法将其动画化到视图中。

【讨论】:

    【解决方案2】:

    我建议你使用bootstrap collapse

    【讨论】:

      【解决方案3】:

      最常用的方法是通过javascript来控制CSS样式,这样(这些只是例子):

      // controlling the opacity of an element
      document.getElementById(yourElementId).style.opacity = 0.5;
      // controlling the position(top) of an element
      document.getElementById(yourElementId).style.top = 10;
      

      您想为您想要做的任何动画创建一组 javascript,并将该代码放入单击时调用的函数中。 淡入效果的示例可能是:

      function myFunction()
      {
      var node=document.createElement("LI");
      var textnode=document.createTextNode("Water");
      
      // fade-in effect. The opacity starts from zero, and increases through 10steps.
      node.style.opacity = 0;
      for (var i=1;i<=10;i++) {
          node.style.opacity = i/10;
      }
      node.style.opacity = 1;
      // end of fade-in effect
      
      node.appendChild(textnode);
      document.getElementById("myList").appendChild(node);
      }
      

      (尚未彻底测试,因此可能会不稳定)

      我的示例是淡入,但只要对任何类型的位置更改或颜色更改或任何类型的更改执行相同操作即可。

      【讨论】:

      • 实际上使用 jQuery 之类的库会更好,但我只是假设您只想使用简单的 javascript,而不要使用其他任何东西。
      【解决方案4】:

      您可以使用 Element.animate()。 更多信息请阅读this

      示例:

          const div = document.createElement('div');
          div.innerText = 'text'; 
          otherElenet.appendChild(div);
          div.animate([
              // keyframes
              { opacity: '0' },
              { opacity: '1' }
          ], {
              // timing options
              duration: 1000,
          });
      

      注意,IE不支持

      【讨论】:

        猜你喜欢
        • 2018-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多