87,907
社区成员
发帖
与我相关
我的任务
分享
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style> </style>
</head>
<body>
</body>
<script>
// 插入样式
function insertCSS(sheet, selector, declare, index){
if(sheet.insertRule){
var insert = selector + '{' + declare + '}';
sheet.insertRule(insert, index);
}else if(sheet.addRule){
sheet.addRule(selector, declare, index);
}
}
// 制造假数据
var styles = [
{selector: '.resize1', declare: 'width:100px;height:100px;border:1px solid red'},
{selector: '.resize2', declare: 'border:1px solid blue'},
{selector: '.resize3', declare: 'border:1px solid yellow'}
];
(function(){
// 第一段样式表
var x = document.styleSheets[0], fragment = document.createDocumentFragment();
for(var i = 0; i < styles.length; i++){
// 插入样式到样式表
var style = styles[i];
insertCSS(x, style.selector, style.declare, i);
// 生成DIV 并对应样式
var odiv = document.createElement('div');
odiv.innerHTML = "test";
odiv.className = style.selector.replace('.','');
fragment.appendChild(odiv);
}
document.body.appendChild(fragment);
})();
</script>
</html>