当前位置: 首页 > 图文教程 > 网页制作 > CSS样式表 > Javascript动态创建 style 节点

CSS样式表
未知长宽元素在已知300px*300px的容器中垂直居中(IE6/7/8/FF)
CSS dashed和dotted的区别
css 超过宽度的文字显示点点
不同浏览器对CSS3和HTML5的支持状况
使用DIV+CSS布局网站的优点和缺陷分析
CSS样式表中的position属性详细说明
css 圆角边框
CSS 网页布局问题 li上多出的margin问题
为什么有些css样式不起作用
tab选项卡布局之利用a的一个选项形式
UL、LI 无序列表实现纯CSS网站导航菜单
在IE下,当margin:0 auto;无法使得块级元素水平居中时
IE bug input 外层浮动的边距问题
重置浏览器默认样式
两种跨浏览器的自适应高的css代码
纯CSS无hacks的跨游览器自适应高度多列布局 推荐
IE中伪类hover的使用及BUG
img与容器下边界的空隙(缝隙) 的解决方法
CSS入门篇之传智播客学习
CSS3 倾斜的网页图片库实例教程

CSS样式表 中的 Javascript动态创建 style 节点


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-12   浏览: 192 ::
收藏到网摘: n/a


有很多提供动态创建 style 节点的方法,但是大多数都仅限于外部的 css 文件。如何能使用程序生成的字符串动态创建 style 节点,我搞了2个小时。
静态外部 css 文件语法:
@import url(style.css);
动态外部 css 文件加载的方法有如下:
第一种:
var style = document.createElement(’link’);
style.href = ’style.css’;
style.rel = ’stylesheet’;
style.type = ‘text/css’;
document.getElementsByTagName(’HEAD’).item(0).appendChild(style);
第二种简单:
document.createStyleSheet(style.css);
动态的 style 节点,使用程序生成的字符串:
var style = document.createElement(’style’);
style.type = ‘text/css’;
style.innerHTML=”body{ background-color:blue; }”;
document.getElementsByTagName(’HEAD’).item(0).appendChild(style);
很遗憾,上面的代码在 ff 里面成功,但是 ie 不支持。从老外论坛得到代码:
var sheet = document.createStyleSheet();
sheet.addRule(’body’,'background-color:red’);
成功,但是很麻烦,要把字符串拆开写,长一点的写死。
接着搜,在一个不知道什么国家的什么语言的 blog 上找到代码:
document.createStyleSheet(”javascript:’body{background-color:blue;’”);
成功,此人实在厉害,但是问题出来了,url 最大 255 个字符,长一点的就不行了,经过 SXPCrazy 提示,改成:
window.style=”body{background-color:blue;”;
document.createStyleSheet(”javascript:style”);
完美解决!!代码:
<html>
<head>
<script>
function blue(){
if(document.all){
window.style="body{background-color:blue;";
document.createStyleSheet("javascript:style");
}else{
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML="body{ background-color:blue }";
document.getElementsByTagName('HEAD').item(0).appendChild(style);
}
}
</script>
</head>
<body>
<input type="button" value="blue" onclick="blue();"/>
</body>
</html>