如何计算子字符串My car is red的第一个字符相对于预定义文本(Burguer rocks.)开头的偏移量?
<pre id="pref-text">
Burguer rocks. <span id="highlight-0">Without cheese please.</span>
Pizzaaaaaa time! <span id="highlight-1">My car is red.</span> blablabla.
</pre>发布于 2015-05-29 05:37:43
HTMLElement.offsetLeft只读方法
返回当前元素的左上角在HTMLElement.offsetParent节点中向左偏移的像素数。
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft
回答你的问题
如何计算“我的车是红色的”的偏移量?
使用javascript元素的.offsetLeft属性。
alert(document.getElementById('highlight-1').offsetLeft);<pre id="pref-text">
Burguer rocks. <span id="highlight-0">Without cheese please.</span>
Pizzaaaaaa time! <span id="highlight-1">My car is red.</span> blablabla.
</pre>
发布于 2015-05-29 21:00:32
我是这样解决的:
var span = document.getElementById('highlight-1');
var offset = 0;
var nextBlock = span.previousSibling;
while (nextBlock != null){
offset = offset + nextBlock.textContent.length;
nextBlock = nextBlock.previousSibling;
}https://stackoverflow.com/questions/30512779
复制相似问题