Javascript 在 createTextNode() 之后更改字体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5549114/
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
Change font after createTextNode()
提问by demas
I need to change the font of element created by the createTextNode() function:
我需要更改由 createTextNode() 函数创建的元素的字体:
var s = document.createTextNode(item.text);
s.setAttribute("font size") = -1;
elem.appendChild(s);
In my code I get error on Firebug:
在我的代码中,我在 Firebug 上遇到错误:
s.setAttribute is not a function
s.setAttribute 不是函数
How can I change a font of created element?
如何更改创建元素的字体?
采纳答案by David Tang
You don't specify font on text nodes, you do so on the parent element- in your case:
您不在文本节点上指定字体,而是在父元素上指定字体- 在您的情况下:
elem.style.fontSize = "20px";
If you don't wish to change the font size for the entire parent element, you can create a <span>
element to wrap around the text node:
如果你不想改变整个父元素的字体大小,你可以创建一个<span>
元素来环绕文本节点:
var span = document.createElement('span');
span.style.fontSize = "20px";
span.appendChild(s);
elem.appendChild(span);
回答by RobG
createTextNode creates a Textnode that has only one method: splitText. setAttributeis a method of the DOM Core that is implemented by the Element interface (i.e. not text nodes).
createTextNode 创建一个只有一种方法的Text节点:splitText。setAttribute是 DOM Core 的一个方法,由 Element 接口(即不是文本节点)实现。
Generally, you should avoid setAttribute as it has numerous quirks and setting the related DOM property is faster and more reliable.
通常,您应该避免使用 setAttribute,因为它有许多怪癖,并且设置相关的 DOM 属性更快、更可靠。
In any case, there is no "fontSize" attribute specified in HTML 4.01 for text nodes so you can't expect browsers to implement it. Text nodes inherit their style from their parent element, so if you want to set the font size of some text, wrap it in an element:
在任何情况下,HTML 4.01 中都没有为文本节点指定“fontSize”属性,因此您不能指望浏览器实现它。文本节点从其父元素继承其样式,因此如果要设置某些文本的字体大小,请将其包装在一个元素中:
window.onload = function() {
var span = document.createElement('span');
// Set DOM property
span.style.fontSize = '200%';
span.appendChild(document.createTextNode('hey'));
// Add to document
document.body.appendChild(span);
};
But in general you are better off to define the style in a class and attach that to the span.
但总的来说,最好在类中定义样式并将其附加到跨度。
回答by gen
maybe you could use inline css. Never tried this with a textnode though
也许你可以使用内联 css。虽然从来没有用 textnode 尝试过这个
setAttribute('style', 'font-size:-1;');