【问题标题】:Remove CSS attribute using Jquery使用 Jquery 删除 CSS 属性
【发布时间】:2011-11-03 05:04:19
【问题描述】:

我发现的所有其他答案都只删除了属性的设置,而不是完全删除了属性。我正在将一个元素从绝对定位更改为固定定位。我需要删除 right 定位属性并将其替换为 margin-right ,以便该元素位于其父 DIV 内。如果未删除 right 属性,则元素会一直移动到屏幕的右侧,而不是像我需要的那样移动到 DIV 的右侧。任何人都可以就如何实现这一点提出建议吗?

【问题讨论】:

    标签: jquery css


    【解决方案1】:

    尝试将其设置为默认值auto

    $(element).css('right', 'auto');
    

    【讨论】:

    • PS - CSS 规范可以为你解答这个问题 - w3.org/TR/CSS21/visuren.html#propdef-right
    • 比明确的硬编码默认值更好的是空字符串(如@Derek 所示),它允许其他样式表规则酌情应用。
    • @Phrogz - 根据 OP 的问题,我认为消隐属性不起作用。 All of the other answers I have discovered only remove the setting of the attribute, and not the attribute completely.
    • 他是对的。在发布此问题之前,我尝试了 Derek 的方法,但没有成功。
    【解决方案2】:
    $('div').css({'right' : '', 'margin-right' : '100px'});
    

    如果这不起作用,请尝试将其设置为默认值auto

    【讨论】:

      【解决方案3】:

      在我看来,最干净的方法是从元素的CSSStyleDeclaration 中完全删除该属性,而不是仅仅用某种空/零/默认值覆盖它:

      $(".foo").prop("style").removeProperty("right");
      $(".foo").prop("style").removeProperty("background-color");
      

      【讨论】:

        【解决方案4】:

        尝试将right 设置为0px,然后设置margin-right

        $('div').css({'right' : '0px', 'margin-right' : '100px'});
        

        【讨论】:

          【解决方案5】:

          你可以试试下面的代码

                  $.fn.removeCss=function(toDelete) {
          
                      var props = $(this).attr('style').split(';');
                      var tmp = -1;
          
                      for( var p=0; p<props.length; p++) {
                          if(props[p].indexOf(toDelete) !== -1 ) {
                              tmp=p
                          }
                      }
          
                      if(tmp !== -1) {
                          props.splice(tmp, 1);
                      }
          
                      return $(this).attr('style',props.join(';'));
                  }
          
          example usage:
          $(selector).removeCss('color');
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-12-19
            • 2011-01-02
            • 1970-01-01
            • 2013-11-24
            • 2012-01-08
            相关资源
            最近更新 更多