如何使用javascript获取HTML文本节点的位置和大小? [英] How to get the position and size of a HTML text node using javascript?

查看:119
本文介绍了如何使用javascript获取HTML文本节点的位置和大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,

<div style="width:100px;text-align:center">text</div>

我想获取文本的位置和大小文本节点,而不是其 div 包装器。

I want to get the position and size of the text text node , not its div wrapper. Is it possible?

推荐答案

在现代浏览器(最近的Mozilla,WebKit和Opera)中,您可以使用 getClientRects()包含文本节点的DOM范围的方法

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>

这篇关于如何使用javascript获取HTML文本节点的位置和大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆