简体   繁体   English

如何更改内容<style type=“text/css”>

[英]How can I change the content of <style type=“text/css”>

I have a page in HTML and I need to replace the content inside tag 我有一个HTML页面,我需要替换标签中的内容

<style type="text/css">
</style>

injecting the content of another .css file hosted on the same domain. 注入同一域中托管的另一个.css文件的内容。

Any idea how to do it in javascript? 任何想法如何做到这一点的JavaScript?

<html>
  <head>
    <style type="text/css">
      h1 {color:red;}
      p {color:blue;}
    </style>
  </head>

  <body>
    <h1>A heading</h1>
    <p>A paragraph.</p>
  </body>
</html>

Add an id attribute to the style tag. 将id属性添加到样式标签。 Use this hook to change the contents of the style tag with Javascript. 使用此钩子可使用Javascript更改样式标签的内容。

HTML 的HTML

<style id="myStyle" type="text/css">
h1 {color:red;}
p {color:blue;}
</style>

<h1>Something</h1>

Javascript Java脚本

var elem = document.getElementById("myStyle");
elem.innerHTML = "h1{color:blue;}";

Working Example http://jsfiddle.net/4xAHr/ 工作示例 http://jsfiddle.net/4xAHr/

If you just want to add those styles, you don't need to inject the content into the style element, just link that other file as a stylesheet: 如果只想添加这些样式,则无需将内容注入到style元素中,只需将该其他文件链接为样式表即可:

var link = document.createElement('link');
link.rel = "stylesheet";
link.href = "/path/to/the/file.css";
document.getElementsByTagName('style')[0].parentNode.appendChild(link);

That will "inject" the relevant styles into the document. 这样会将相关样式“注入”到文档中。

Live Example using your markup | 使用标记的实时示例 Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM