网页制作 
首页 > 网页制作 > 浏览文章

Javascript动态创建 style 节点

(编辑:jimmy 日期: 2024/5/30 浏览:3 次 )

有很多提供动态创建 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>
上一篇:CSS网页设计技巧十则
下一篇:让XHTML元素的命名规则更加合理
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网