如何获得包装内容的左上角位置?

时间:2018-01-22 14:45:27

标签: javascript html

我需要识别HTML节点的左上角,以便我可以指向该位置的箭头。但是,当节点的内容换行时,这会变得棘手,因为节点的top,left,bottom和right属性定义的框不再与实际节点匹配。举个例子,下面是示例HTML和JSFiddle,我想得到突出显示的句子中第一个单词的确切位置:

<div class="container">
This is the first sentence. <span id="highlight">This is the second sentence, but it is so long, that it wraps to the next line, making it's starting point hard to identify.</span>  This is the last sentence and it doesn't matter.
</div>

https://jsfiddle.net/c2cf1oe7/

我觉得它应该很简单,但到目前为止,我还没弄清楚。

1 个答案:

答案 0 :(得分:0)

span是一个内联元素,因此通常它没有偏移和位置,如top,left,width ......

See Here

在这种情况下,您需要在#highlight

旁边添加一个范围

&#13;
&#13;
var v=document.getElementById('highlight').offsetLeft;
document.getElementById('mark').style.left=v+'px';
&#13;
.container {
  position:relative;
  width: 300px;
}

#highlight {
  border:1px solid black;
  background-color: yellow;
}

#mark{
  width:3px;
  height:3px;
  border:1px solid red;
  position: absolute;
}
&#13;
<html>
<body>
<div class="container">
<div id="mark"></div>
<span>This is the first sentence.</span><span id="highlight">This is the second sentence, but it is so long, that it wraps to the next line.</span>
</div>
</body>
</html>
&#13;
&#13;
&#13;

如您所见,#mark现在位于#highlight的左上角