这些答案大多数现在已经过时,IE7支持不再是问题。
支持IE11 +和所有现代浏览器 的最佳方法是:
const $elem = $("#elem");$elem[0].style.setProperty('width', '100px', 'important');或者,如果需要,您可以创建一个小型jQuery插件来执行此操作。该插件
css()在其支持的参数中紧密匹配jQuery自己的方法:
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');


