码迷,mamicode.com
首页 > Web开发 > 详细

IE8、7、6动态添加样式时,CSS hack的BUG

时间:2017-09-12 13:47:31      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:img   rip   ges   div   star   文章   nts   tle   绿色   

问题描述

下面这段CSS代码通过JS动态添加,结果会怎样呢?

.box {
    background: red; /* normal browsers */
    *background: blue;  /* IE 6 and 7 */
    _background: green; /* IE6 */
}

 通过以下代码添加到页面中

var node = document.createElement(‘style‘);
node.type = ‘text/css‘;
if (node.styleSheet) {        // for w3c
	node.styleSheet.cssText = style;
} else {        // for ie
	node.appendChild(document.createTextNode(style));
}
document.getElementsByTagName(‘head‘)[0].appendChild(node);

从代码来看,>=IE8和现代浏览器的.box的颜色是红色的,IE7是蓝色的,IE6是绿色的,那么实际呢?

IE6:

技术分享

IE7:

技术分享

IE8:

技术分享

Chrome:

技术分享

 

怎么回事???

 

技术分享

 

从上面的截图可以看到,只有Chrome和IE6是正常的,IE7和IE8表现有问题。

IE7的表现为使用了IE6 hack(_ hack)

IE8的表现为使用了IE7 hack(* hack)

解决方法

直接上代码:

var node = document.createElement(‘style‘);
node.type = ‘text/css‘;
document.getElementsByTagName(‘head‘)[0].appendChild(node);
if (node.styleSheet) {        // for w3c
	node.styleSheet.cssText = style;
} else {        // for ie
	node.appendChild(document.createTextNode(style));
}

其实没什么变化,就是移动了appendChild那一句代码的位置。

由原来的先添加CSS样式,然后再添加到head上,变成了先添加到head上面,再更新CSS样式。

再次刷新IE7、8,现在的表现正常了。

 

贴上测试代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	.box{
		width: 100px;
		height: 100px;
	}
	</style>
</head>
<body>
	<div class="box"></div>
	<script>
	var node = document.createElement(‘style‘),
		style = ‘.box {background: red;*background: blue;_background: green;}‘;
	node.type = ‘text/css‘;
	document.getElementsByTagName(‘head‘)[0].appendChild(node);
	if (node.styleSheet) {        // for w3c
		node.styleSheet.cssText = style;
	} else {        // for ie
		node.appendChild(document.createTextNode(style));
	}
	</script>
</body>
</html>

 

参考文章:https://www.phpied.com/the-star-hack-in-ie8-and-dynamic-stylesheets/

IE8、7、6动态添加样式时,CSS hack的BUG

标签:img   rip   ges   div   star   文章   nts   tle   绿色   

原文地址:http://www.cnblogs.com/ystrdy/p/7509062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!