• 在IE8中如何通过javascripts改变<style />中的内容?


    1.createStyleSheet()

    if(document.createStyleSheet){
       var cssStyle=document.createStyleSheet();  //兼容ie8
       cssStyle.cssText=cssStr;     //要添加的css
    }
     http://www.zhihu.com/question/21799414
    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>

  • 相关阅读:
    线性代数思维导图——3.向量
    微分中值定理的基础题型总结
    构造函数
    Python课程笔记(七)
    0241. Different Ways to Add Parentheses (M)
    0014. Longest Common Prefix (E)
    0013. Roman to Integer (E)
    0011. Container With Most Water (M)
    0010. Regular Expression Matching (H)
    0012. Integer to Roman (M)
  • 原文地址:https://www.cnblogs.com/zhengyan/p/4981485.html
Copyright © 2020-2023  润新知