Может ли это решение быть совместимым с IE7 и IE6?

Есть ли способ сделать это решение совместимым с 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, но мне потребуется мой собственный код для работы в

6
задан Community 23 May 2017 в 11:51
поделиться