简体   繁体   English

在createTextNode()之后更改字体

[英]Change font after createTextNode()

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? 如何更改已创建元素的字体?

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);

createTextNode creates a Text node that has only one method: splitText. createTextNode创建一个只有一个方法的Text节点:splitText。 setAttribute is a method of the DOM Core that is implemented by the Element interface (ie not text nodes). 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. 在任何情况下,HTML 4.01中都没有为文本节点指定“fontSize”属性,因此您不能指望浏览器实现它。 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: 文本节点从其父元素继承其样式,因此如果要设置某些文本的字体大小,请将其包装在元素中:

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. 但总的来说,最好在类中定义样式并将其附加到跨度。

maybe you could use inline css. 也许你可以使用内联css。 Never tried this with a textnode though 从来没有尝试过使用textnode

setAttribute('style', 'font-size:-1;');

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

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