【问题标题】:How can I calculate a span's offset inside preformated text?如何计算预格式化文本中的跨度偏移量?
【发布时间】:2015-05-28 16:59:35
【问题描述】:

如何计算子字符串 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>

【问题讨论】:

  • 您的意思是跨度的x, y 位置,相对于其父项?还是您的意思是子字符串“My car is red”中第一个字符相对于“Berguer Rocks...blablabla”字符串开头的位置?
  • 子字符串第一个字符相对于文本开头的位置

标签: html text offset


【解决方案1】:

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>

【讨论】:

    【解决方案2】:

    我是这样解决的:

    var span = document.getElementById('highlight-1');
    
    var offset = 0;
    var nextBlock = span.previousSibling;
    
    while (nextBlock != null){
        offset = offset + nextBlock.textContent.length;
        nextBlock = nextBlock.previousSibling;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多