Javascript 通过javascript动态添加css到页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4847313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:22:57  来源:igfitidea点击:

Dynamically add css to page via javascript

javascriptcss

提问by John Smith

I'm making a widget that will be added to external websites, and I have made a page that generates css for them to style it (text color, background color, font size, etc). I end up with a textarea filled with css for them to copy/paste to their website.

我正在制作一个将添加到外部网站的小部件,并且我制作了一个页面,可以为它们生成 css 来设置样式(文本颜色、背景颜色、字体大小等)。我最终得到了一个装满 css 的 textarea 供他们复制/粘贴到他们的网站。

Is there a way to add this css to the current page in order to have a live preview?

有没有办法将此 css 添加到当前页面以进行实时预览?

回答by vogdb

if you want to add css text

如果你想添加css文本

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = 'content';
document.getElementsByTagName('head')[0].appendChild(style);

if you want to add css file

如果你想添加css文件

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', 'css/my.css');
document.getElementsByTagName('head')[0].appendChild(link);

回答by Josh K

I have traditionally appended a <style>block when doing elements.

我传统上<style>在做元素时附加了一个块。

var style_rules = [];

style_rules.push("#" + myElemId + " { /* Rules */ } ");
/* ... */

var style = '<style type="text/css">' + style_rules.join("\n") + "</style>";
$("head").append(style);

An important thing to note is that because you don't know what any of the existing styles is, or what id's might conflict on the page, it's very useful to keep track of your id's inside your JavaScript application, then using those to populate the injected <style>block. I also tend to run my names through a prefix function to ensure that the generic names of wrapper, and unitdo not conflict (they are turned into something like myunique_wrapperand myunique_unit.

需要注意的重要一点是,因为您不知道任何现有样式是什么,或者id页面上可能有什么冲突,所以在 JavaScript 应用程序中跟踪您的 id 非常有用,然后使用这些来填充注入的<style>块。我也倾向于通过前缀功能来运行我的名字,以保证通用名称wrapper,而unit不会发生冲突(它们都变成像myunique_wrappermyunique_unit

Incorporating a basic CSS reset like #myWrapper {margin: 0; padding: 0}can be a decent starting platform for building your own custom styles.

结合一个基本的 CSS 重置#myWrapper {margin: 0; padding: 0}可以是一个不错的起始平台,用于构建您自己的自定义样式。

Addressing your unique case, a live preview so to speak, I would designate a div with standard elements. Then when they click "update" read in the rules and append them to the head. If you want to negate any residual effects from past rules you can remove the last <style>element or better yet give your <style>element an id. I'm not sure if that kind of selection would work, but it should.

针对您的独特情况,可以说是实时预览,我会指定一个带有标准元素的 div。然后当他们点击“更新”时,读入规则并将它们附加到头部。如果您想消除过去规则的任何残留影响,您可以删除最后一个<style>元素,或者更好地为您的<style>元素提供一个 id。我不确定这种选择是否可行,但应该可行。

回答by Konstantin Tarkus

var element = document.createElement('style');
element.setAttribute('type', 'text/css');

if ('textContent' in element) {
  element.textContent = css;
} else {
  element.styleSheet.cssText = css;
}

document.getElementsByTagName('head')[0].appendChild(element);

回答by Antoine Latter

Can you add a styletag to the DOM, with the contents of the text-area in it? You may want to give it an id so you can change it later.

style能在 DOM 中添加一个标签,其中包含文本区域的内容吗?您可能想要给它一个 id,以便您以后可以更改它。

回答by RichardTheKiwi

I recommend you start using a decent framework for your web/JavaScript development, personally I'd go with jQuery.

我建议你开始为你的 web/JavaScript 开发使用一个像样的框架,我个人会使用 jQuery。

http://api.jquery.com/css/

There are some code snippets here that show you how to quickly set css properties for elements.

这里有一些代码片段向您展示如何快速设置元素的 css 属性。