如何计算子串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>
答案 0 :(得分:0)
HTMLElement.offsetLeft 只读方法返回当前元素的左上角在{{3}内向左偏移的像素数} node HTMLElement.offsetParent
如何计算&#34;我的车是红色&#34;?
的偏移量
使用javascript元素的.offsetLeft
属性。
alert(document.getElementById('highlight-1').offsetLeft);
&#13;
<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>
&#13;
答案 1 :(得分:0)
我解决了这个问题:
var span = document.getElementById('highlight-1');
var offset = 0;
var nextBlock = span.previousSibling;
while (nextBlock != null){
offset = offset + nextBlock.textContent.length;
nextBlock = nextBlock.previousSibling;
}