小编典典

如何使用.css()应用!important?

html

我在应用的样式时遇到了麻烦!important。我试过了:

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

什么都不做 ;
不会应用任何宽度样式。有没有一种类似jQuery的方式来应用这种样式而不必覆盖cssText(这意味着我需要先对其进行解析,等等)?

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

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


阅读 519

收藏
2020-05-10

共1个答案

小编典典

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

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

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

或者,如果需要,您可以创建一个小型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;
};



// 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');
2020-05-10