2009-11-05 14 views
5

Tengo que obtener cuáles son todos los estilos CSS que se usan en un archivo HTML usando JavaScript.Obtener todos los css utilizados en el archivo html

<html> 
    <head> 
     <style type="text/css"> 
      body { 
       border: 1px solid silver; 
      } 
      .mydiv{ 
       color: blue; 
      } 
     </style> 
    </head> 
    <body> 
    </body> 
</html> 

Si el código anterior es mi HTML, tengo que escribir una función de JavaScript dentro del encabezado que devuelve una cadena como esta.

body { 
    border: 1px solid silver; 
} 
.mydiv { 
    color: blue; 
} 

¿Es posible hacer?

Respuesta

7

Para hojas de estilo en línea, puede obtener el contenido del DOM normal, como con cualquier otro elemento:

document.getElementsByTagName('style')[0].firstChild.data 

Para link, hojas de estilo ed externos es más problemático. En los navegadores modernos, puede obtener el texto de cada regla (incluidas las hojas de estilo en línea, vinculadas y @importadas) de la propiedad document.styleSheets[].cssRules[].cssText.

Desafortunadamente IE no implementa este estándar DOM Level 2 Style/CSS, sino que usa la versión its own subtly different de las interfaces StyleSheet y CSSRule. Por lo tanto, necesita un código de sniff-y-branch para recrear las reglas en IE, y el texto puede no ser exactamente el mismo que el original. (En particular, IE ALL-CAPS sus nombres de propiedades y perder espacio en blanco.)

var css= []; 

for (var sheeti= 0; sheeti<document.styleSheets.length; sheeti++) { 
    var sheet= document.styleSheets[sheeti]; 
    var rules= ('cssRules' in sheet)? sheet.cssRules : sheet.rules; 
    for (var rulei= 0; rulei<rules.length; rulei++) { 
     var rule= rules[rulei]; 
     if ('cssText' in rule) 
      css.push(rule.cssText); 
     else 
      css.push(rule.selectorText+' {\n'+rule.style.cssText+'\n}\n'); 
    } 
} 

return css.join('\n'); 
+1

¿Realmente llaman las variables sheeti ?? :) Es de hecho una variable sheeti .. – Faruz

+0

Gracias bobince ... Funcionó bien en todos los navegadores ... – DonX

+1

Me sale el siguiente error: 'TypeError: No se puede leer la propiedad 'length' de null' – starbeamrainbowlabs

0

Aquí está mi solución:

function getallcss() { 
    var css = "", //variable to hold all the css that we extract 
     styletags = document.getElementsByTagName("style"); 

    //loop over all the style tags 
    for(var i = 0; i < styletags.length; i++) 
    { 
     css += styletags[i].innerHTML; //extract the css in the current style tag 
    } 

    var currentsheet = false;//initialise a variable to hold a reference to the stylesheet we are currently extracting from 
    //loop over all the external stylesheets 
    for(var i = 0; i < document.styleSheets.lenngth; i++) 
    { 
     currentsheet = document.styleSheets[i]; 
     //loop over all the styling rules in this external stylesheet 
     for(var e = 0; e , currentsheet.cssRules.length; e++) 
     { 
      css += currentsheet.cssRules[e].cssText; //extract all the styling rules 
     } 
    } 

    return css; 
} 

Se basa en la respuesta de @ bobince.

Extrae todos los CSS tanto de las etiquetas de estilo como de las hojas de estilo externas.

2

aquí está mi solución:

var css = []; 
for (var i=0; i<document.styleSheets.length; i++) 
{ 
    var sheet = document.styleSheets[i]; 
    var rules = ('cssRules' in sheet)? sheet.cssRules : sheet.rules; 
    if (rules) 
    { 
     css.push('\n/* Stylesheet : '+(sheet.href||'[inline styles]')+' */'); 
     for (var j=0; j<rules.length; j++) 
     { 
      var rule = rules[j]; 
      if ('cssText' in rule) 
       css.push(rule.cssText); 
      else 
       css.push(rule.selectorText+' {\n'+rule.style.cssText+'\n}\n'); 
     } 
    } 
} 
var cssInline = css.join('\n')+'\n'; 

Al final, cssInline es una lista textual de todos los steelsheets de la página y su contenido.

Ejemplo:

/* Stylesheet : http://example.com/cache/css/javascript.css */ 
.javascript .de1, .javascript .de2 { -webkit-user-select: text; padding: 0px 5px; vertical-align: top; color: rgb(0, 0, 0); border-left-width: 1px; border-left-style: solid; border-left-color: rgb(204, 204, 204); margin: 0px 0px 0px -7px; position: relative; background: rgb(255, 255, 255); } 
.javascript { color: rgb(172, 172, 172); } 
.javascript .imp { font-weight: bold; color: red; } 

/* Stylesheet : http://example.com/i/main_master.css */ 
html { } 
body { color: rgb(24, 24, 24); font-family: 'segoe ui', 'trebuchet MS', 'Lucida Sans Unicode', 'Lucida Sans', sans-serif; font-size: 1em; line-height: 1.5em; margin: 0px; padding: 0px; background: url(http://pastebin.com/i/bg.jpg); } 
a { color: rgb(204, 0, 51); text-decoration: none; } 
a:hover { color: rgb(153, 153, 153); text-decoration: none; } 
.icon24 { height: 24px; vertical-align: middle; width: 24px; margin: 0px 4px 0px 10px; } 
#header { border-radius: 0px 0px 6px 6px; color: rgb(255, 255, 255); background-color: rgb(2, 56, 89); } 
#super_frame { min-width: 1100px; width: 1200px; margin: 0px auto; } 
#monster_frame { -webkit-box-shadow: rgb(204, 204, 204) 0px 0px 10px 5px; box-shadow: rgb(204, 204, 204) 0px 0px 10px 5px; border-radius: 5px; border: 1px solid rgb(204, 204, 204); margin: 0px; background-color: rgb(255, 255, 255); } 
#header a { color: rgb(255, 255, 255); } 
#menu_2 { height: 290px; } 

/* Stylesheet : [inline styles] */ 
.hidden { display: none; } 
Cuestiones relacionadas