有什么方法可以使这个解决方案兼容IE6和IE7吗?
http://jsfiddle.net/kirkstrobeck/sDh7s/1/
摘自这个问题
我认为我已经找到了一个真正的解决方案。我把它做成了一个新的函数:
jQuery.style(name, value, priority);
你可以像使用.css('name')
一样,使用.style('name')
来获取值,使用.style()
获取CSSStyleDeclaration,并且还可以设置值——同时指定优先级为“important”。请参见https://developer.mozilla.org/en/DOM/CSSStyleDeclaration。
演示
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
函数
// For those who need them (< IE 9), add support for CSS functions
var isStyleFuncSupported = CSSStyleDeclaration.prototype.getPropertyValue != null;
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(RegExp.escape(styleName) + '\\s*:\\s*' + RegExp.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(RegExp.escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?', 'gmi');
return rule.test(this.cssText) ? 'important' : '';
}
}
// Escape regex chars with \
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
// The style function
jQuery.fn.style = function(styleName, value, priority) {
// DOM node
var node = this.get(0);
// Ensure we have a DOM node
if (typeof node == 'undefined') {
return;
}
// CSSStyleDeclaration
var style = this.get(0).style;
// Getter/Setter
if (typeof styleName != 'undefined') {
if (typeof value != 'undefined') {
// Set style property
var priority = typeof priority != 'undefined' ? priority : '';
style.setProperty(styleName, value, priority);
} else {
// Get style property
return style.getPropertyValue(styleName);
}
} else {
// Get CSSStyleDeclaration
return style;
}
}
请参考https://developer.mozilla.org/en/DOM/CSSStyleDeclaration了解如何读取和设置CSS值的示例。我的问题在于,我已经在我的CSS中将宽度设置为
!important
,以避免与其他主题CSS冲突,但是我在jQuery中对宽度进行的任何更改都不会受到影响,因为它们将被添加到style属性中。
兼容性
使用setProperty
函数进行优先级设置,http://help.dottoro.com/ljdpsdnb.php说支持IE 9+和所有其他浏览器。我已经尝试过IE 8,但失败了,这就是为什么我在我的函数中构建了对其的支持(请参见上文)。它将适用于使用setProperty的所有其他浏览器,但需要我的自定义代码才能在< IE 9中运行。