本文介绍了如何使用 .css() 应用 !important?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用 !important 样式时遇到问题.我试过了:

I am having trouble applying a style that is !important. I’ve tried:

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

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

This does nothing; no width style whatsoever is applied. Is there a jQuery-ish way of applying such a style without having to overwrite cssText (which would mean I’d need to parse it first, etc.)?

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

Edit: I should add that I have a stylesheet with an !important style that I am trying to override with an !important style inline, so using .width() and the like does not work since it gets overridden by my external !important style.

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

Also, the value that will override the previous value is computed, so I cannot simply create another external style.

推荐答案

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

Most of these answers are now outdated, IE7 support is not an issue.

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

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

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

/**
 * 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');

此处为 jsfiddle 示例.

这篇关于如何使用 .css() 应用 !important?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 11:24