简体   繁体   中英

Add CSS gradient with javascript - bug in IE7

I am trying to add gradient on only .link.box.gradient but in ie7 it add on .link.box.gradient and .style.box.gradient

<!DOCTYPE html>
<html lang="sv">
    <head>
    <title></title>
        <script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.min.js"></script>
        <script>
            jQuery(function ($) {
                $('head').append("<style>.link.box{height:100px;width:100px;}.link.box.gradient{filter:progid:DXImageTransform.Microsoft.gradient(startColorStr='#000000',EndColorStr='#ffffff');}</style>");
            });
        </script>
    </head>
    <body>
        <div class="style box gradient">Gradient (style-tag)</div>
        <div class="link box gradient">Gradient (link-tag)</div>
    </body>
</html>

You can see here too, http://jsfiddle.net/Zhvpy/ One strange thing is when i move out .link.box{height:100px;width:100px;} from javascript as you can see here http://jsfiddle.net/Zhvpy/1 it seems to work, but I dont want to move out.

Why is it like this? How can I fix this bug?

removed original incorrect answer

EDIT 1

Odd - decided it might be the way older versions of IE handle certain elements (like <script /> ) so tried a non-jQuery solution . Seems to work!

EDIT 2

Added this to your full script - outputs different results which are more in line with what IE8 outputs

function appendStyle(element, cssObj) {
    //$('#a').append($('<span/>').text(cssObjToText(cssObj)));
    if ($.browser.version == 7) {
        var head = document.getElementsByTagName('head')[0],
            style = document.createElement('style'),
            rules = document.createTextNode(cssObjToText(cssObj));

        style.type = 'text/css';

        head.appendChild(style);

        style.styleSheet.cssText = rules.nodeValue;
    }
    else {
        element.after('<style class="css-finalized">' + cssObjToText(cssObj) + '</style>');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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