我想找出div中角色的位置。
e.g。
<div>This is a very long multi-line text that overflows and wraps<div>
我想在第24位找到角色的绝对x和y位置(即&#39; - &#39;)。这可能吗?
答案 0 :(得分:0)
这是一种在普通JavaScript中获取文本偏移位置而不用文本包含元素的方法:
var characters = document.querySelector('.characters');
var charactersText = characters.textContent;
var charAtIndex = 25;
var offsetPosition;
characters.textContent = '';
for (var i = 0; i < charactersText.length; i++) {
var textNode = document.createTextNode(charactersText[i]);
characters.appendChild(textNode);
if (i === charAtIndex) {
var range = document.createRange();
range.selectNodeContents(textNode);
var rects = range.getClientRects();
offsetPosition = {
left: rects[0].left,
top: rects[0].top
};
}
}
alert(JSON.stringify(offsetPosition, null, 2));
<div class="characters">This is a very long multi-line text that overflows and wraps</div>