我有以下 html:
<span as="0" style="display: block; -webkit-user-select: text; ">
"[TEXT]"
<span id="as_cursor" style="padding: 0px; margin:0px; width: 0px;"></span>
"[TEXT]"
</span>
我使用内部跨度作为标记,稍后使用 jquery.offset() 从中获取坐标。当此跨度与行尾重合时(在屏幕上呈现,实际文本中没有 eol 字符),内部跨度呈现在外部元素的开头(左上角),因此给出错误的偏移量 (0,0) .
有什么办法可以避免这种行为?目前只需要兼容 chrome 和 mozilla。
最佳答案
你没有得到偏移量的原因是因为 span 元素是内联的。要解决此问题,请将以下代码添加到 HTML 页面的 header 部分:
<style>
.offsetFixed {
display: inline-block;
}
#outerSpan {
display: block;
-webkit-user-select: text;
}
#as_cursor {
padding: 0;
margin: 0;
width: 0;
}
</style>
此外,对您的 HTML 进行以下修改:
<span class="offsetFixed" id="outerSpan" as="0">"[TEXT]"
<span class="offsetFixed" id="as_cursor"></span>"[TEXT]"
</span>
然后您可以使用 jQuery 获取正确的偏移量:
$(document).ready(function () {
var offset = $("#as_cursor").offset();
alert(JSON.stringify(offset));
});
关于javascript - 带有文本兄弟错位的 html 内联节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7464646/