How to get the position and size of a HTML text node using javascript?

后端 未结 1 1623
别跟我提以往
别跟我提以往 2021-02-02 14:01

For Example,

text

I want to get the position and size of the text t

相关标签:
1条回答
  • 2021-02-02 14:41

    In modern browsers (recent-ish Mozilla, WebKit and Opera) you can use the getClientRects() method of a DOM range that encompasses the text node.

    var textNode = document.getElementById("wombat").firstChild;
    var range = document.createRange();
    range.selectNodeContents(textNode);
    var rects = range.getClientRects();
    if (rects.length > 0) {
        console.log("Text node rect: ", rects[0]);
    }
    <div id="wombat">Wombat</div>

    0 讨论(0)
提交回复
热议问题