Change font after createTextNode()

前端 未结 3 1353
天涯浪人
天涯浪人 2021-01-11 16:22

I need to change the font of element created by the createTextNode() function:

var s = document.createTextNode(item.text);
s.setAttribute(\"font size\") = -1         


        
相关标签:
3条回答
  • 2021-01-11 16:46

    createTextNode creates a Text node that has only one method: splitText. setAttribute is a method of the DOM Core that is implemented by the Element interface (i.e. not text nodes).

    Generally, you should avoid setAttribute as it has numerous quirks and setting the related DOM property is faster and more reliable.

    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:

    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.

    0 讨论(0)
  • 2021-01-11 16:46

    maybe you could use inline css. Never tried this with a textnode though

    setAttribute('style', 'font-size:-1;');
    
    0 讨论(0)
  • 2021-01-11 16:48

    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:

    var span = document.createElement('span');
    span.style.fontSize = "20px";
    span.appendChild(s);
    elem.appendChild(span);
    
    0 讨论(0)
提交回复
热议问题