Есть ли способ сделать это решение совместимым с IE6 и IE7?
http://jsfiddle.net/kirkstrobeck/sDh7s/1/
Думаю, я нашел реальное решение. Я превратил его в новую функцию:
jQuery.style (имя, значение, приоритет);
Вы можете использовать его для получения значений с помощью .style ('name ')
, как и .css (' name ')
, получите CSSStyleDeclaration с помощью .style ()
, а также установите значения - с возможностью указать приоритет как' важный'. См. 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. Моя проблема заключалась в том, что я уже установил ! Important
для ширины в моем CSS, чтобы избежать конфликтов с другими CSS темами, но любые изменения, внесенные мной в ширину в jQuery, не будут затронуты, поскольку они будут добавлены в атрибут стиля.
Для установки с приоритетом с помощью функции setProperty
, http://help.dottoro.com/ljdpsdnb.php говорит о поддержке IE 9+. и все остальные браузеры. Я пробовал использовать IE 8, и он потерпел неудачу, поэтому я встроил его поддержку в свои функции (см. Выше). Он будет работать во всех других браузерах, использующих setProperty, но мне потребуется мой собственный код для работы в