【问题标题】:toggleClass animation not working? or need help toggling animationtoggleClass 动画不起作用?或需要帮助切换动画
【发布时间】:2013-09-04 02:30:36
【问题描述】:

我正在使用此代码:

 $('#products h2').click(
        function() {
           $('.well').toggleClass('margin-left260', 100000);
            return false;
        }
    );

我想要做的是使用左边距将 div 滑动超过 260,然后让它在单击时滑回 0。我不明白为什么 .toggleClass 不适合我。

我之前使用 .animate(margin-left,'260px); 也做得很好但是对于我的生活来说,我可以弄清楚如何使用切换使其返回到 0 的边距。我在这里缺少什么?

【问题讨论】:

  • 页面里有没有jQuery ui库也可以分享html和css
  • “我的 CSS 是可预测的”?这是什么意思?
  • 我要找的是html...因为有必要重新创建问题
  • 你也在使用 twitter bootstrap
  • 你从哪里得知 toggleClass 的第二个参数与动画有关?

标签: jquery toggle toggleclass


【解决方案1】:

我在这里添加了一个 jsfiddle 示例 - http://jsfiddle.net/BaXyR/

基本上

$('.clickme').click(function(){
if($('#moveme').hasClass('marginleft260')){
      $('#moveme').animate({
        marginLeft: "-=260px",
      }, 5000, function() {
        $(this).removeClass('marginleft260');
      });    
}else{
      $('#moveme').animate({
        marginLeft: "+=260px",
      }, 5000, function() {
        $(this).addClass('marginleft260');
      });    
}
});

【讨论】:

    【解决方案2】:

    toggleClass 可用于在切换开关上添加/删除一个/类。 margin-left260 是你的css中的一个类,即

    .margin-left260 {
        margin-left:260px;
    }
    

    同时查看您的代码,我认为您没有正确实现 toggleClass。见:http://api.jquery.com/toggleClass/

    您是否要为运动设置动画?

    我认为正确的代码是使用 animate 函数 - 请参阅:http://api.jquery.com/animate/

    【讨论】:

    • 是的,它是一个类。它成功地将边距放入左侧,但没有对其进行动画处理。
    • 好的,太好了。 Animate 运行良好,但我无法获得第二次点击以将其返回到 margin-left 0
    • 我认为您需要在 if 语句中使用 hasClass('margin-left260') ,然后如果是,则以另一种方式制作动画。
    猜你喜欢
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 2010-12-13
    • 2021-08-26
    相关资源
    最近更新 更多