Javascript 我可以在innerHTML 中添加样式标签吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26890675/
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
Can I add a style tag to innerHTML?
提问by John
I'm trying to post an innerHTML table. Would like the font size in one cell to be bigger. Is it possible to include a style tag like so?
我正在尝试发布一个innerHTML 表。希望一个单元格中的字体大小更大。是否可以包含这样的样式标签?
cell4.innerHTML = "<style: font-size:40px>" + "John Doe" + "</style>" + "</br>";
I tried the following fiddle, but it isn't working. http://jsfiddle.net/s1dj3x8e/
我尝试了以下小提琴,但它不起作用。http://jsfiddle.net/s1dj3x8e/
回答by Drew Kennedy
The <style>tag is meant to be a container for CSS code inside the head, so what you're trying to accomplish cannot be done with that element in this context.
该<style>标签旨在成为头部内 CSS 代码的容器,因此您无法在此上下文中使用该元素完成您要完成的工作。
Try replacing the following line:
尝试替换以下行:
cell4.innerHTML = "<style: font-size:40px>" + "John Doe" + "</style>" + "</br>";
With:
和:
cell4.innerHTML = "<span style='font-size:40px'>John Doe</span>";
Updated fiddle (now with spaninstead of divas correctly pointed out by Zach below):
更新的小提琴(现在span而不是div像下面扎克正确指出的那样):
回答by Zach Saucier
Style tags are meant to contain CSS blocks including selectors, allowing them to style multiple elements at a time. All of the CSS for the style tag should go between the <style>tags themselves.
样式标签旨在包含包括选择器在内的 CSS 块,允许它们一次设置多个元素的样式。style 标签的所有 CSS 都应该位于<style>标签本身之间。
To do what you're trying to do, you need to return an element that either uses a class that has defined styles or inline styles like so:
要执行您要执行的操作,您需要返回一个元素,该元素使用已定义样式或内联样式的类,如下所示:
cell4.innerHTML = '<span style="font-size:40px">John Doe</span>';
OR
或者
cell4.innerHTML = '<span class="fs40">John Doe</span>';
where the CSS .fs40 { font-size:40px; }in your stylesheet.
.fs40 { font-size:40px; }样式表中的 CSS在哪里。

