代码之家  ›  专栏  ›  技术社区  ›  mkoryak

如何申请!使用.css()很重要吗?

  •  653
  • mkoryak  · 技术社区  · 16 年前

    我很难运用一种 !important . 我尝试过:

    $("#elem").css("width", "100px !important");
    

    这确实 没有什么 ;不应用任何宽度样式。有没有一种jquery风格的方法可以应用这种风格而不必覆盖 cssText (这意味着id需要首先解析它,等等)?

    编辑 :我应该添加一个样式表 !重要的 我试图用一个 !重要的 内联样式,因此使用 .width() 因为它被我的外部 !重要的 风格。

    另外,将覆盖上一个值的值 计算 ,所以我不能简单地创建另一个外部样式。

    30 回复  |  直到 7 年前
        1
  •  306
  •   RevanthKrishnaKumar V. Glen Best    10 年前

    我想我找到了一个真正的解决办法。我把它变成了一个新的函数:

    jQuery.style(name, value, priority);

    你可以用它来获取 .style('name') 就像 .css('name') ,获取cssstyledeclaration .style() ,还可以设置值-具有将优先级指定为“重要”的功能。见 this .

    演示

    var div = $('someDiv');
    console.log(div.style('color'));
    div.style('color', 'red');
    console.log(div.style('color'));
    div.style('color', 'blue', 'important');
    console.log(div.style('color'));
    console.log(div.style().getPropertyPriority('color'));
    

    输出如下:

    null
    red
    blue
    important
    

    函数

    (function($) {    
      if ($.fn.style) {
        return;
      }
    
      // Escape regex chars with \
      var escape = function(text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
      };
    
      // For those who need them (< IE 9), add support for CSS functions
      var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
      if (!isStyleFuncSupported) {
        CSSStyleDeclaration.prototype.getPropertyValue = function(a) {
          return this.getAttribute(a);
        };
        CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) {
          this.setAttribute(styleName, value);
          var priority = typeof priority != 'undefined' ? priority : '';
          if (priority != '') {
            // Add priority manually
            var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) +
                '(\\s*;)?', 'gmi');
            this.cssText =
                this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
          }
        };
        CSSStyleDeclaration.prototype.removeProperty = function(a) {
          return this.removeAttribute(a);
        };
        CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
          var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?',
              'gmi');
          return rule.test(this.cssText) ? 'important' : '';
        }
      }
    
      // The style function
      $.fn.style = function(styleName, value, priority) {
        // DOM node
        var node = this.get(0);
        // Ensure we have a DOM node
        if (typeof node == 'undefined') {
          return this;
        }
        // CSSStyleDeclaration
        var style = this.get(0).style;
        // Getter/Setter
        if (typeof styleName != 'undefined') {
          if (typeof value != 'undefined') {
            // Set style property
            priority = typeof priority != 'undefined' ? priority : '';
            style.setProperty(styleName, value, priority);
            return this;
          } else {
            // Get style property
            return style.getPropertyValue(styleName);
          }
        } else {
          // Get CSSStyleDeclaration
          return style;
        }
      };
    })(jQuery);
    

    有关如何读取和设置css值的示例。我的问题是我已经 !important 为了避免与其他主题css的宽度冲突,我在jquery中对宽度所做的任何更改都不会受到影响,因为它们将被添加到style属性中。

    兼容性

    用于使用 setProperty 函数, This Article 表示支持IE9+和所有其他浏览器。我尝试过使用IE8,但失败了,这就是为什么我在函数中构建了对它的支持(见上文)。它可以在使用setproperty的所有其他浏览器上工作,但需要我的自定义代码才能在<ie 9中工作。

        2
  •  543
  •   David Thomas    13 年前

    这个问题是由jquery不理解 !important 属性,因此无法应用规则。

    你也许可以解决这个问题,并通过引用它来应用规则,通过 addClass() :

    .importantRule { width: 100px !important; }
    
    $('#elem').addClass('importantRule');
    

    或通过使用 attr() :

    $('#elem').attr('style', 'width: 100px !important');
    

    不过,后一种方法将取消先前设置的任何内嵌样式规则。所以小心使用。

    当然,有一个很好的论点是,@nick craver的方法更容易/更明智。

    以上, () 稍微修改以保持原始的方法 style 字符串/属性:

    $('#elem').attr('style', function(i,s) { return s + 'width: 100px !important;' });
    
        3
  •  138
  •   Nick Craver    16 年前

    您可以直接使用 .width() 这样地:

    $("#elem").width(100);
    

    更新评论: 您也有这个选项,但它将替换元素上的所有css,因此不确定它是否更可行:

    $('#elem').css('cssText', 'width: 100px !important');
    
        4
  •  68
  •   BettaSplendens    12 年前
    var elem = $("#elem");
    elem[0].style.removeAttribute('width');
    elem[0].style.setProperty('width', '100px', 'important');
    
        5
  •  51
  •   Community Mohan Dere    9 年前

    David Thomas’s answer 描述一种使用方法 $('#elem').attr('style', …) ,但警告使用它将删除 style 属性。这里有一种使用方法 attr() 没有这个问题:

    var $elem = $('#elem');
    $elem.attr('style', $elem.attr('style') + '; ' + 'width: 100px !important');
    

    作为功能:

    function addStyleAttribute($element, styleAttribute) {
        $element.attr('style', $element.attr('style') + '; ' + styleAttribute);
    }
    
    addStyleAttribute($('#elem'), 'width: 100px !important');
    

    这里是一个 JS Bin demo .

        6
  •  27
  •   Nate    11 年前

    在阅读了其他答案并进行了实验之后,这就是我的工作:

    $(".selector")[0].style.setProperty( 'style', 'value', 'important' );
    

    不过,这在IE8及以下版本中不起作用。

        7
  •  22
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    你可以这样做:

    $("#elem").css("cssText", "width: 100px !important;");
    

    使用“csstext”作为属性名,并以您希望添加到css中的任何内容作为其值。

        8
  •  17
  •   chharvey    10 年前

    您可以通过两种方式实现这一点:

    $("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
    $("#elem").attr("style", "width: 100px !important");
    
        9
  •  14
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    不需要去复杂的@aramkocharyan的答案,也不需要动态插入任何样式标签。

    只是覆盖样式, 但是 你不需要解析任何东西,为什么?

    // Accepts the hyphenated versions (i.e. not 'cssFloat')
    function addStyle(element, property, value, important) {
        // Remove previously defined property
        if (element.style.setProperty)
            element.style.setProperty(property, '');
        else
            element.style.setAttribute(property, '');
    
        // Insert the new style with all the old rules
        element.setAttribute('style', element.style.cssText +
            property + ':' + value + ((important) ? ' !important' : '') + ';');
    }
    

    不能使用 removeProperty() ,因为它不会删除 !important Chrome中的规则。
    不能使用 element.style[property] = '' ,因为它只接受firefox中的camelcase。

    您可以使用jquery缩短这个时间,但是这个普通的函数将在现代浏览器、internetexplorer8等上运行。

        10
  •  12
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    这是我遇到这个问题后所做的…

    var origStyleContent = jQuery('#logo-example').attr('style');
    jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');
    
        11
  •  9
  •   A J A Y shashwat    9 年前

    此解决方案不覆盖任何以前的样式,只应用您需要的样式:

    var heightStyle = "height: 500px !important";
    if ($("foo").attr('style')) {
      $("foo").attr('style', heightStyle + $("foo").attr('style').replace(/^height: [-,!,0-9,a-z, A-Z, ]*;/,''));
    else {
      $("foo").attr('style', heightStyle);
    }
    
        12
  •  9
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    如果它不是那么相关,并且因为你在处理一个元素 #elem ,您可以将其ID更改为其他内容,并根据需要进行样式设置…

    $('#elem').attr('id', 'cheaterId');
    

    在你的css中:

    #cheaterId { width: 100px;}
    
        13
  •  8
  •   Sebastian Zartner Emmanouil Chountasis    11 年前

    而不是使用 css() 函数尝试 addClass() 功能:

      <script>
      $(document).ready(function() {
        $("#example").addClass("exampleClass");
      });
      </script>
    
      <style>
      .exampleClass{
        width:100% !important;
        height:100% !important;
      }
      </style>
    
        14
  •  8
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    对我来说,解决这个问题最简单、最好的方法就是使用addClass()而不是.css()或.attr()。

    例如:

    $('#elem').addClass('importantClass');

    在你的css文件中:

    .importantClass {
        width: 100px !important;
    }
    
        15
  •  6
  •   Álvaro González    10 年前

    仅供参考,它不工作,因为jquery不支持它。有张2012年的罚单( #11173 $(elem).css("property", "value !important") fails )最终被封为wontfix。

        16
  •  6
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    我们需要先去掉以前的款式。我用正则表达式删除它。以下是更改颜色的示例:

    var SetCssColorImportant = function (jDom, color) {
           var style = jDom.attr('style');
           style = style.replace(/color: .* !important;/g, '');
           jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
    
        17
  •  6
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    在head中附加样式的另一种方法:

    $('head').append('<style> #elm{width:150px !important} </style>');
    

    这将在所有css文件之后追加样式,因此它将比其他css文件具有更高的优先级,并将被应用。

        18
  •  6
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    可能是这样的:

    隐藏物

    var node = $('.selector')[0];
    OR
    var node = document.querySelector('.selector');
    

    设置CSS

    node.style.setProperty('width', '100px', 'important');

    删除CSS

    node.style.removeProperty('width');
    OR
    node.style.width = '';
        19
  •  4
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    我想你试过了,没有加 !important ?

    内联css(这就是javascript添加样式的方式)覆盖样式表css。即使样式表css规则 !重要的 .

    另一个问题(也许是一个愚蠢的问题,但必须被问到):你正在努力研究的元素是什么? display:block; display:inline-block; ?

    不知道你在css方面的专业知识…内联元素的行为并不总是如您所期望的那样。

        20
  •  4
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    这样做:

    $("#elem").get(0).style.width= "100px!important";
    
        21
  •  4
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    我认为它工作正常,可以覆盖以前的任何其他css(this:dom元素):

    this.setAttribute('style', 'padding:2px !important');
    
        22
  •  4
  •   Sebastian Luna    7 年前

    此解决方案将保留所有计算的javascript并将重要标记添加到元素中: 可以(例如,如果需要用重要标记设置宽度)

    $('exampleDiv').css('width', '');
    //This will remove the width of the item
    var styles = $('exampleDiv').attr('style');
    //This will contain all styles in your item
    //ex: height:auto; display:block;
    styles += 'width: 200px !important;'
    //This will add the width to the previous styles
    //ex: height:auto; display:block; width: 200px !important;
    $('exampleDiv').attr('style', styles);
    //This will add all previous styles to your item
    
        23
  •  3
  •   Tim Cutting    12 年前

    它可能适合您的情况,也可能不适合您的情况,但您可以在许多此类情况下使用css选择器。

    例如,如果您希望.csstext的第3和第6个实例具有不同的宽度,则可以编写:

    .cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}
    

    或:

    .container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}
    
        24
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    我们可以使用setproperty或csstext来添加 !important 到使用javascript的dom元素。

    例1:

    elem.style.setProperty ("color", "green", "important");
    

    例2:

    elem.style.cssText='color: red !important;'
    
        25
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    三个工作实例

    我也遇到过类似的情况,但在与.closest()斗争了很长一段时间后,我使用了.find(),其中有很多变体。

    示例代码

    // Allows contain functions to work, ignores case sensitivity
    
    jQuery.expr[':'].contains = function(obj, index, meta, stack) {
        result = false;
        theList = meta[3].split("','");
        var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
        for (x=0; x<theList.length; x++) {
            if (contents.toLowerCase().indexOf(theList[x].toLowerCase()) >= 0) {
                return true;
            }
        }
        return false;
    };
    
    $(document).ready(function() {
        var refreshId = setInterval( function() {
            $("#out:contains('foo', 'test456')").find(".inner").css('width', '50px', 'important');
        }, 1000); // Rescans every 1000 ms
    });
    

    替代方案

    $('.inner').each(function () {
        this.style.setProperty('height', '50px', 'important');
    });
    
    $('#out').find('.inner').css({ 'height': '50px'});
    

    工作: http://jsfiddle.net/fx4mbp6c/

        26
  •  2
  •   Austin    12 年前

    我还发现某些元素或附加组件(如bootstrap)有一些特殊的类情况,它们不能很好地处理 !important 或其他类似的工作 .addClass/.removeClass ,因此必须打开/关闭它们。

    例如,如果您使用 <table class="table-hover"> 成功修改行的颜色等元素的唯一方法是 table-hover 上下课,像这样

    $(your_element).closest("table").toggleClass("table-hover");

    希望这项工作将有助于有人!:)

        27
  •  2
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    当“事件”时,我试图更改菜单项的文本颜色时遇到了同样的问题。当我遇到同样的问题时,我发现最好的办法是:

    第一步:在css中创建一个新的类,用于此目的,例如:

    .colorw{ color: white !important;}
    

    最后一步:使用addClass方法应用该类,如下所示:

    $('.menu-item>a').addClass('colorw');
    

    问题解决了。

        28
  •  2
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    最安全的解决方法是添加一个类,然后在css中使用魔法:-), addClass() removeClass() 应该做这项工作。

        29
  •  1
  •   Razan Paul    9 年前

    https://jsfiddle.net/xk6Ut/256/

    另一种方法是在javascript中动态创建和更新css类。为此,我们可以使用style元素,并且需要使用style元素的id,以便我们可以更新css类

    function writeStyles(styleName, cssText) {
        var styleElement = document.getElementById(styleName);
        if (styleElement) document.getElementsByTagName('head')[0].removeChild(
            styleElement);
        styleElement = document.createElement('style');
        styleElement.type = 'text/css';
        styleElement.id = styleName;
        styleElement.innerHTML = cssText;
        document.getElementsByTagName('head')[0].appendChild(styleElement);
    }
    

      var cssText = '.testDIV{ height:' + height + 'px !important; }';
      writeStyles('styles_js', cssText)
    
        30
  •  -6
  •   Marcel Gwerder ericlucas23    12 年前

    另一个解决此问题的简单方法是添加样式属性:

    $('.selector').attr('style', 'width:500px !important');