How to dynamically create CSS class in IE8

2019-02-26 02:17发布

I need to create a CSS stylesheet class dynamically using JavaScript in IE8.

I have used following code for other browsers:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);

it's working fine in all browsers except IE8. How to achieve the same in IE8?

1条回答
贪生不怕死
2楼-- · 2019-02-26 02:53

According to MSDN:

The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.

So, try to use innerText to write these class.

Updated:

You can use:

style.styleSheet.cssText = '.cssClass { color: #F00; }';

Or do a test:

if (style.styleSheet){
    style.styleSheet.cssText = '.cssClass { color: #F00; }';
} else {
    style.appendChild(document.createTextNode('.cssClass { color: #F00; }'));
}

Hope, it now runs! :)

查看更多
登录 后发表回答