如何申请!重要的是使用.css()?

mko*_*yak 700 html javascript css jquery

我在应用一种风格时遇到了麻烦!important.我试过了:

$("#elem").css("width", "100px !important");
Run Code Online (Sandbox Code Playgroud)

什么都不做 ; 没有任何宽度样式应用.是否有jQuery-ish方式应用这样的样式而不必覆盖cssText(这意味着我需要先解析它等等)?

编辑:我应该补充一点,我有一个样式表!important,我试图用!important样式内联覆盖一个样式,所以使用等等.width()不起作用,因为它被我的外部!important样式覆盖.

此外,将覆盖以前的值的值进行计算,所以我不能简单地创建另一个外部风格.

Dav*_*mas 577

问题是由jQuery不理解该!important属性引起的,因此无法应用该规则.

您可以解决该问题,并通过引用来应用规则,方法是addClass():

.importantRule { width: 100px !important; }

$('#elem').addClass('importantRule');
Run Code Online (Sandbox Code Playgroud)

或者使用attr():

$('#elem').attr('style', 'width: 100px !important');
Run Code Online (Sandbox Code Playgroud)

然而,后一种方法将取消任何先前设置的内联样式规则.所以要小心使用.

当然,有一个很好的论据,@ Nick Craver的方法更容易/更明智.

上面的attr()方法略有修改,以保留原始style字符串/属性:

$('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });
Run Code Online (Sandbox Code Playgroud)

  • 样式为空时小修复:$('#elem').attr('style',function(i,s){return(s ||'')+'width:100px!important;'}); (14认同)
  • 你应该添加@falko的修复,就像在firefox中你的最后一个片段将样式设置为''undefinedwidth:100px!important;'`当前样式为空时. (4认同)
  • 我倾向于你的后一种方法,但令人遗憾的是,生病可能最终不得不解析以前的cssText因为我不能丢弃它 (2认同)

Ara*_*yan 329

我想我找到了一个真正的解决方案.我把它变成了一个新功能:

jQuery.style(name, value, priority);

你可以用它来获取值.style('name')一样.css('name'),获得与CSSStyleDeclaration上.style(),并设置值-有能力来指定优先级为"重要".看到这个.

演示

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'));
Run Code Online (Sandbox Code Playgroud)

这是输出:

null
red
blue
important
Run Code Online (Sandbox Code Playgroud)

功能

(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);
Run Code Online (Sandbox Code Playgroud)

请参见有关如何读取和设置CSS值的例子.我的问题是我已经!important在我的CSS中设置宽度以避免与其他主题CSS发生冲突,但是我在jQuery中对宽度所做的任何更改都不会受到影响,因为它们会被添加到style属性中.

兼容性

为了使用该setProperty功能进行优先级设置,本文称支持IE 9+和所有其他浏览器.我已经尝试使用IE 8并且它已经失败了,这就是为什么我在我的函数中构建了对它的支持(参见上文).它将适用于使用setProperty的所有其他浏览器,但它需要我的自定义代码才能在<IE 9中工作.

  • $('.someclass').each(function(){this.style.setProperty('border','none','important');}); http://stackoverflow.com/questions/11962962/overwriting-important-with-css-or-jquery更简单,更清洁,更高效. (13认同)
  • @Richard,处理这个问题的唯一好方法是*不要*在你的风格中使用`!important`,至少对于你将要用jQuery改变的东西......只要它们是*你的*风格.如果你的代码在一个学生编写的页面中运行,而这个学生通过在每一个样式上打"!important"来解决他对特殊性规则的无知,那么你迟早要先将这些`!importants`推向其中一个. (3认同)
  • 几年前还发布了[jQuery.important插件](https://github.com/premasagar/important).我在生产中使用它只有一个小问题(请参阅他们的问题选项卡. (2认同)
  • 解决此问题的唯一好方法是使用类,而不是直接样式注入。 (2认同)

Nic*_*ver 143

您可以直接使用.width()如下设置宽度:

$("#elem").width(100);
Run Code Online (Sandbox Code Playgroud)

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

$('#elem').css('cssText', 'width: 100px !important');
Run Code Online (Sandbox Code Playgroud)

  • 防止覆盖`$('#elem').css('cssText',$('#elem').css('cssText')+'width:100px!important');`用前一个值连接它 (10认同)

小智 76

var elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案之一.简单而且有效.而且它不需要太多解释.除了jQuery选择器之外,它只是常规的JavaScript.jQuery不提供对"重要"的支持,所以使用常规JS是要走的路 (10认同)
  • 在vanilla JS中,removeAttribute不起作用.请执行下列操作.`var style = document.getElementById('elem'); style.removeProperty( '宽度'); style.setProperty('width,'100px','important')` (3认同)
  • 如果你想用它去Vanilla,只需制作`var = document.getElementById('elem');`并在elem上执行样式方法(而不是elem [0]).干杯. (2认同)
  • 还有`.removeAttribute`的问题.它似乎是一个[IE-only方法](http://help.dottoro.com/ljhutuuj.php).@mcoenca评论是对的; `.removeProperty`工作正常.根据[MSDN](https://msdn.microsoft.com/en-us/library/ff975224%28v=vs.85%29.aspx)它是IE9 + (2认同)
  • @Dejan,很抱歉很晚才回答,但这应该有效:`elem.next().get(0).style ...` (2认同)

Ror*_*ane 54

David Thomas的回答描述了一种使用方法$('#elem').attr('style', …),但警告说使用它将删除style属性中先前设置的样式.这是一种attr()没有这个问题的使用方法:

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

作为一个功能:

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

这是一个JS Bin演示.

  • 也可以修改`addStyleAttribute()`以获取与[jQuery的`.css()`](http://api.jquery.com/css/#css2)相同的参数.例如,它可以支持将CSS属性的映射到其值.如果你这样做,你基本上会重新实现`.css()`并修复`!important`错误但没有任何优化. (2认同)

Nat*_*ate 29

在阅读其他答案并进行实验后,这对我有用:

$(".selector")[0].style.setProperty( 'style', 'value', 'important' );
Run Code Online (Sandbox Code Playgroud)

但是,这在IE 8及以下版本中不起作用.


haw*_*126 26

你可以这样做:

$("#elem").css("cssText", "width: 100px !important;");
Run Code Online (Sandbox Code Playgroud)

使用"cssText"作为属性名称以及您想要添加到CSS的任何值作为其值.

  • 这样做的缺点是它会覆盖之前存在的任何 `cssText` - 所以你不能真正自由地使用它 (5认同)
  • 无论如何,你可以使用 $("#elem").css("cssText", "+=;width: 100px !important;"); (2认同)

mko*_*yak 20

大多数这些答案现在已经过时,IE7 支持不是问题。

支持 IE11+ 和所有现代浏览器的最佳方法是:

const $elem = $("#elem");
$elem[0].style.setProperty('width', '100px', 'important');
Run Code Online (Sandbox Code Playgroud)

或者,如果您愿意,您可以创建一个小型 jQuery 插件来执行此操作。这个插件css()在它支持的参数上与 jQuery 自己的方法非常匹配:

/**
 * Sets a CSS style on the selected element(s) with !important priority.
 * This supports camelCased CSS style property names and calling with an object 
 * like the jQuery `css()` method. 
 * Unlike jQuery's css() this does NOT work as a getter.
 * 
 * @param {string|Object<string, string>} name
 * @param {string|undefined} value
 */   
jQuery.fn.cssImportant = function(name, value) {
  const $this = this;
  const applyStyles = (n, v) => {
    // Convert style name from camelCase to dashed-case.
    const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
      return m1 + "-" + upper.toLowerCase() + m2;
    }); 
    // Loop over each element in the selector and set the styles.
    $this.each(function(){
      this.style.setProperty(dashedName, v, 'important');
    });
  };
  // If called with the first parameter that is an object,
  // Loop over the entries in the object and apply those styles. 
  if(jQuery.isPlainObject(name)){
    for(const [n, v] of Object.entries(name)){
       applyStyles(n, v);
    }
  } else {
    // Otherwise called with style name and value.
    applyStyles(name, value);
  }
  // This is required for making jQuery plugin calls chainable.
  return $this;
};
Run Code Online (Sandbox Code Playgroud)
// Call the new plugin:
$('#elem').cssImportant('height', '100px');

// Call with an object and camelCased style names:
$('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});

// Call on multiple items:
$('.item, #foo, #bar').cssImportant('color', 'red');

Run Code Online (Sandbox Code Playgroud)

示例 jsfiddle 在这里


kva*_*kva 18

您可以通过两种方式实现此目的:

$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");
Run Code Online (Sandbox Code Playgroud)


Has*_*own 14

没有必要考虑@ 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' : '') + ';');
}
Run Code Online (Sandbox Code Playgroud)

无法使用removeProperty(),因为它不会删除!importantChrome 中的规则.
无法使用element.style[property] = '',因为它只接受Firefox中的camelCase.

你可以用jQuery缩短它,但这个vanilla函数可以在现代浏览器,Internet Explorer 8等上运行.


keb*_*ang 12

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

var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');
Run Code Online (Sandbox Code Playgroud)


Sin*_*nan 9

如果它不是那么相关,并且因为你正在处理一个元素#elem,你可以将它的id更改为其他东西并根据你的意愿设置它...

$('#elem').attr('id', 'cheaterId');
Run Code Online (Sandbox Code Playgroud)

在你的CSS中:

#cheaterId { width: 100px;}
Run Code Online (Sandbox Code Playgroud)

  • 为什么你更改id来应用css而不是只添加一个css类? (9认同)

Ala*_*ois 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);
}
Run Code Online (Sandbox Code Playgroud)


小智 8

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

  <script>
  $(document).ready(function() {
    $("#example").addClass("exampleClass");
  });
  </script>

  <style>
  .exampleClass{
    width:100% !important;
    height:100% !important;
  }
  </style>
Run Code Online (Sandbox Code Playgroud)

  • 这确实是一个完全合理的问题解决方案......只是不**这个**问题! (2认同)

Jac*_*eld 8

对我来说这个问题的最简单和最好的解决方案是简单地使用addClass()而不是.css()或.attr().

例如:

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

在你的CSS文件中:

.importantClass {
    width: 100px !important;
}
Run Code Online (Sandbox Code Playgroud)

  • 由于宽度是在 JavaScript 中计算的,这并不能解决问题。 (2认同)

Álv*_*lez 7

仅供参考,它不起作用,因为jQuery不支持它.2012年有一张票(#11173 $(elem).css("属性","价值!重要")失败)最终被关闭为WONTFIX.


Rod*_*ues 6

我们首先需要删除以前的样式.我使用正则表达式删除它.这是一个改变颜色的例子:

var SetCssColorImportant = function (jDom, color) {
       var style = jDom.attr('style');
       style = style.replace(/color: .* !important;/g, '');
       jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
Run Code Online (Sandbox Code Playgroud)

  • 不知道为什么这么多解决方案在cssText方法工作正常时将样式标记破解到元素上...例如`$ selector.css('cssText','margin-bottom:0!important')` (3认同)

h0m*_*yun 6

在头部追加样式的另一种方法:

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

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


Ser*_*zN1 6

可能看起来像这样:

高速缓存

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 = '';


nob*_*_tq 6

我认为它工作正常,并且可以覆盖之前的任何其他CSS(此:DOM元素):

this.setAttribute('style', 'padding:2px !important');
Run Code Online (Sandbox Code Playgroud)


小智 5

像这样做:

$("#elem").get(0).style.width= "100px!important";
Run Code Online (Sandbox Code Playgroud)


Seb*_*dro 5

此解决方案将保留所有计算出的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
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

529675 次

最近记录:

5 年,9 月 前