2016-09-06 55 views
1

我需要使用CSS样式获取完整的HTML文档,而无需实际使用外部CSS文件。通过Javascript将外部CSS样式表转换为嵌入样式,或转换为<style>标记

例如我需要这个...

的index.html

<head> 
    <link rel="stylesheet" href="css/styles.css"> 
</head> 

<body> 
    <div id="foo">Test</div> 
</body> 

CSS/Styles.css中

#foo { 
    color: red; 
} 

...变换变成某物像任FF的,以便:

1)中的所有外部CSS样式是直列d入元件

的index.html

<head> 
    <link rel="stylesheet" href="css/styles.css"> 
</head> 

<body> 
    <div id="foo" style="color:red;">Test</div> 
</body> 

OR

2)款式内嵌-D为<style>标签

的index.html

<head> 
    <link rel="stylesheet" href="css/styles.css"> 
    <style>#foo { color: red; }</style> 
</head> 

<body> 
    <div id="foo">Test</div> 
</body> 

那是可行的香草的Javascript/jQuery的?谢谢。

+0

可能是的,但为什么? – Roberrrt

+0

这个工具可以让你内联样式https://putsmail.com/tests/new –

+0

是的......但是你做了什么?作为参考,你可以使用'jquery.getStyleObject.js'插件从https://gist.github.com/surjikal/3007123 –

回答

0

我有第二种情况的解决方案。使用AJAX调用来获取文件的内容为字符串和文档

var css = '.popover { background-color: #666666; color: #ffffff';    
head = document.head || document.getElementsByTagName('head')[0], 
style = document.createElement('style'); 
style.type = 'text/css'; 
if (style.styleSheet){ 
    style.styleSheet.cssText = css; 
} else { 
    style.appendChild(document.createTextNode(css)); 
} 
head.appendChild(style); 
0

在香草的JavaScript,你可以简单地做一个HTTP请求,以获得css/styles.css文件的内容中添加动态创建的风格标签,然后创建一个新的style元素。沿着这些线:

var head = document.head || document.getElementsByTagName('head')[0], 
    xhttp = new XMLHttpRequest(); 

xhttp.open('GET', '/css/styles.css'); 
xhttp.onreadystatechange = function() { 
    if (xhttp.readyState === 4) { 
    if (xhttp.status === 200) { 
     var style = document.createElement('style'); 
     style.type = 'text/css'; 
     if (style.styleSheet) { 
     style.styleSheet.cssText = xhttp.responseText; 
     } else { 
     style.appendChild(document.createTextNode(xhttp.responseText)); 
     } 
     head.appendChild(style); 
    } else { 
     console.log("Error", xhttp.statusText); 
    } 
    } 
} 
xhttp.send();