【问题标题】:How do I add a style element to a div and remove it using javascript如何将样式元素添加到 div 并使用 javascript 将其删除
【发布时间】:2013-04-12 21:12:15
【问题描述】:

当用户单击按钮触发事件时,我想为 div 元素添加 margin-left css 样式,然后在用户再次单击按钮时将其删除。

这是 div 元素:

<div id="container" class="content">

Javascript 应将其更改为:

<div id="container" class="content" style="margin-left:354px">

最好使用动画,让它看起来是向左滑动而不是跳跃。

【问题讨论】:

  • 纯javascript还是jquery?

标签: javascript jquery


【解决方案1】:

在事件监听器中试试这个:

var cont = document.getElementById("container");
cont.style.marginLeft = cont.style.marginLeft === "354px" ? "auto" "354px";

这不会对其进行动画处理。您可以考虑为此使用 CSS:

#container {
    transition: margin-left ease 500ms;
}

但如果你想支持旧版浏览器和 IE9,请选择 soyuka 的答案。

【讨论】:

    【解决方案2】:

    在发布此类问题之前,您应该阅读manual...

    $('.content').animate({'margin-left':'354px'}, 1000); 
    //where 1000 is the animation time in ms
    

    回滚:

    $('.content').animate({'margin-left':'auto'}); //or your previous value
    

    【讨论】:

      【解决方案3】:

      试试这个解决方案,我刚刚进入 JSBin:http://jsbin.com/oyemen/1/edit

      【讨论】:

      • 虽然这在理论上可以回答这个问题,it would be preferable 在此处包含答案的基本部分,并提供链接以供参考。
      【解决方案4】:

      您可以将jQuery.animatemargin-left css 属性一起使用。 animate 的第二个参数是持续时间(以毫秒为单位)。还有许多其他设置可以更好地控制动画(例如,缓入或缓出)。

      $('#container').animate({'margin-left':'354px'},3000); 
      

      然后将其移回相反的位置

      $('#container').animate({'margin-left':'0px'},3000); 
      

      现场示例:http://jsfiddle.net/xdpCs/1/

      【讨论】:

      • 完美,谢谢。经验很少,所以活生生的例子帮助了我
      • @Jamiec 打败了我。就连 soyuka 的回答都被否决了,而且都非常好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 2016-07-14
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多