定位工具提示/弹出窗口通常只是使用 getBoundingClientRect() 或 jQuery 的 offset() 函数(内部使用 getBoundingClientRect)来获取相对于文档或窗口,但如果您在某些 Webkit 浏览器上放大,这些函数就会开始返回意外/错误的结果,因为 getBoundingClientRect 函数在 Webkit 中实现得很奇怪。这一直是一个问题,并且由于某种原因从未得到解决。
问题:如何(如果可能的话)在不使用 getBoundingClientRect() 的情况下计算元素相对于文档的精确像素偏移量,以便值不> 改变缩放?
最佳答案
我能够在 https://jsbin.com/vaculorita/1/edit?css,js,output 中解决这个问题
我不确定 jQuery 的偏移量想要做什么,但是切换到绝对定位和手动使用 getBoundingClientRect 的组合对我来说很有效。
HTML
<div id="tooltip">Tooltip</div>
<input type="text" id="username">
CSS
#username {
margin-left: 54px;
margin-top: 21px;
}
#tooltip {
position: absolute;
left: 0;
top:0;
}
JS
$(function() {
function moveTooltip() {
var $tooltip = $('#tooltip').first();
var $input = $('#username').first();
var rect = $input.get(0).getBoundingClientRect();
$tooltip.css('left', rect.left + $input.width());
$tooltip.css('top', rect.top + $input.height());
}
moveTooltip();
$(window).on('resize scroll', moveTooltip);
});
关于javascript - 获取相对于文档的元素偏移量,无需 getBoundingClientRect(Webkit bug),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40444057/