在IE8中如何通过javascripts改变<style />中的内容?
1.createStyleSheet()
createStyleSheet 语法
以下为引用内容: oStylesheet = object.createStyleSheet( [sURL] [, iIndex])
参数:
sURL 可选,字符串(string),指定怎样将样式规则加入文档,如果是一个文件名,样式信息将作为 link 对象加入;如果包含样式信息,则作为 style 对象加入。
iIndex 可选,整数值(integer),指定加入的样式信息在 stylesheets 集合里的索引序号,默认为加入到 stylesheets 集合的最后。
返回值:
ostylesheet 对象(Element),返回一个 stylesheet 对象
使用javascript进行样式的定义。
第一种:
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{ }”;
document.getElementsByTagName(’HEAD’).item(0).appendChild(style);
但是在上面只能在Firefox兼容,在IE里却不支持。
var sheet = document.createStyleSheet();
sheet.addRule(’body’,'
如果按照上面的话就能成功,但是很麻烦,要把字符串拆开写。
我一直在搜索着用javascript定义样式的代码,终于找到了,代码如下。
document.createStyleSheet(”javascript:’body{’”);
但用上面的javascript代码唯一的缺点就是url 最大 255 个字符,长一点的就不行了,经过 SXPCrazy 提示,将代码进行修改成如下:
window.style=”body{”;
document.createStyleSheet(”javascript:style”);
完美解决!!代码:
<script>
function blue(){
if(document.all){
window.style="body{";
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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程