简体   繁体   English

这个解决方案可以兼容IE7和IE6吗?

[英]Can this solution be IE7 and IE6 compatible?

Is there any way to make this solution IE6 and IE7 compatible? 有没有办法使这个解决方案IE6和IE7兼容?

http://jsfiddle.net/kirkstrobeck/sDh7s/1/ http://jsfiddle.net/kirkstrobeck/sDh7s/1/


Pulled from this question 这个问题拉出来

I think I've found a real solution. 我想我找到了一个真正的解决方案。 I've made it into a new function: 我把它变成了一个新功能:

jQuery.style(name, value, priority);

You can use it to get values with .style('name') just like .css('name') , get the CSSStyleDeclaration with .style() , and also set values - with the ability to specify the priority as 'important'. 您可以使用.style('name')获取值,就像.css('name') ,使用.style()获取CSSStyleDeclaration,以及设置值 - 可以将优先级指定为'important' 。 See https://developer.mozilla.org/en/DOM/CSSStyleDeclaration . 请参阅https://developer.mozilla.org/en/DOM/CSSStyleDeclaration

Demo 演示

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

Here's the output: 这是输出:

null
red
blue
important

The Function 功能

// 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;
    }
}

See https://developer.mozilla.org/en/DOM/CSSStyleDeclaration for examples of how to read and set the CSS values. 有关如何读取和设置CSS值的示例,请参阅https://developer.mozilla.org/en/DOM/CSSStyleDeclaration My issue was that I had already set !important for the width in my CSS to avoid conflicts with other theme CSS, but any changes I made to the width in jQuery would be unaffected since they would be added to the style attribute. 我的问题是我已经设置了!important对我的CSS中的宽度!important以避免与其他主题CSS发生冲突,但是我对jQuery中的宽度所做的任何更改都不会受到影响,因为它们会被添加到style属性中。

Compatibility 兼容性

For setting with the priority using the setProperty function, http://help.dottoro.com/ljdpsdnb.php says there is support for IE 9+ and all other browsers. 要使用setProperty函数进行优先级设置, http//help.dottoro.com/ljdpsdnb.php表示支持IE 9+和所有其他浏览器。 I have tried with IE 8 and it has failed, which is why I built support for it in my functions (see above). 我已经尝试过使用IE 8但它失败了,这就是为什么我在我的函数中建立了对它的支持(见上文)。 It will work on all other browsers using setProperty, but it will need my custom code to work in < IE 9. 它将适用于使用setProperty的所有其他浏览器,但它需要我的自定义代码才能在<IE 9中工作。

That looks needlessly complicated.. I would just use em based font size for the tags inside the container and adjust the container's font size using percents. 这看起来不必要复杂..我只是使用基于em的字体大小的容器内的标签,并使用百分比调整容器的字体大小。 That way all the tag inside container get automatically resized.. 这样,容器内的所有标签都会自动调整大小。

JsFiddle: http://jsfiddle.net/qqxe9/ JsFiddle: http//jsfiddle.net/qqxe9/

CSS: CSS:

.container {
 font-size:100%;   
}

p {
 font-size:1em;   
}

JS JS

function changeFontSize(n)
{
    var size = $('.container').data('size');
    size += n * 10;
    $('.container').css('font-size',size+'%').data('size',size);
}


$(document).ready(function(){
        $('body').prepend(' \
            <div class="font-size-changer"> \
                <a href="#" class="decrease">A&darr;</a> \
                <!--<a href="#" class="reset">A</a>--> \
                <a href="#" class="increase">A&uarr;</a> \
                <a href="#" class="null">null</a> \
            </div> \
        ').find('> .container').data('size',100);
        
        
        $('.font-size-changer .increase').click(
            function() 
            {
                changeFontSize(1);  
            }
        );
        
        $('.font-size-changer .decrease').click(
            function() 
            {
                changeFontSize(-1);  
            }
        );
});

I've stripped the saving to cookie part but that's easy enough to re-apply.. 我已将保存删除到cookie部分,但这很容易重新应用..

The one trick is to save the initial percentage somewhere (i used data()) because if you try to retrieve it with .css('font-size') it'll give you the calculated size (eg '16px'). 一个技巧是在某处保存初始百分比(我使用data()),因为如果你试图用.css('font-size')检索它,它会给你计算的大小(例如'16px')。 There might be a way to get the value as a percentage but can't remember how. 可能有一种方法可以将值作为百分比获得但不记得如何。

When re-applying the cookie saving part, remember to set the initial data() to the value in the cookie instead of 100%, then call changeFontSize(0) to apply it. 重新应用cookie保存部分时,请记住将初始data()设置为cookie中的值而不是100%,然后调用changeFontSize(0)来应用它。

Anyway, this code works in IE6. 无论如何,这段代码适用于IE6。

You won't be able to get this working in IE 6 or 7 as it is. 您将无法在IE 6或7中实现此功能。 I would suggest instead creating new style rules, which can include !important declarations and can be achieved in all major browsers using something like the following function. 我建议改为创建新的样式规则,其中可以包括!important声明,并且可以使用类似下面的函数在所有主流浏览器中实现。 It would require your elements to be identifiable via a selector, such as an ID selector (which would necessitate adding IDs to the elements if not present), and only creates style rules rather than retrieving them, although this is fine for your example. 它需要通过选择器识别您的元素,例如ID选择器(如果不存在则需要向元素添加ID),并且只创建样式规则而不是检索它们,尽管这对您的示例很好。

I've updated your example and it now works in all major browsers, including IE 6 and 7: http://jsfiddle.net/9ZZVP/1/ 我已经更新了你的例子,它现在适用于所有主流浏览器,包括IE 6和7: http//jsfiddle.net/9ZZVP/1/

Style rule creation code: 样式规则创建代码:

var addRule;

if (typeof document.styleSheets != "undefined" && document.styleSheets) {
    addRule = function(selector, rule) {
        var styleSheets = document.styleSheets, styleSheet;
        if (styleSheets && styleSheets.length) {
            styleSheet = styleSheets[styleSheets.length - 1];
            if (styleSheet.addRule) {
                styleSheet.addRule(selector, rule)
            } else if (typeof styleSheet.cssText == "string") {
                styleSheet.cssText = selector + " {" + rule + "}";
            } else if (styleSheet.insertRule && styleSheet.cssRules) {
                styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
            }
        }
    }
} else {
    addRule = function(selector, rule, el, doc) {
        el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
    };
}

function createCssRule(selector, rule, doc) {
    doc = doc || document;
    var head = doc.getElementsByTagName("head")[0];
    if (head && addRule) {
        var styleEl = doc.createElement("style");
        styleEl.type = "text/css";
        styleEl.media = "screen";
        head.appendChild(styleEl);
        addRule(selector, rule, styleEl, doc);
        styleEl = null;
    }
}

Example usage: 用法示例:

createCssRule("#foo", "background-color: purple !important;");

Go to http://www.javascriptlint.com/online_lint.php 访问http://www.javascriptlint.com/online_lint.php

Paste your Javascript there. 将Javascript粘贴到那里。

You will see there are quite a few warnings. 你会看到有很多警告。 To start, fix all of the warnings. 首先,修复所有警告。 Once JavaScript Lint no longer generates warnings, test it in IE. 一旦JavaScript Lint不再生成警告,请在IE中测试它。 That should at least get you started down the path of finding a solution. 这应该至少让你开始寻找解决方案的道路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM