当调用getBoundingClientRect
svg 中的 div 以相应地定位 svg 之外的其他元素时,只有 Chrome (78.0.3904.108) 和 Windows 10 上的top
和left
值太高。
这是一个演示问题的代码笔。绿色框周围的红色边框使用getBoundingClientRect
svg 中元素的坐标定位。在 Windows Chrome 上,您会看到top
和left
值以某种方式被夸大的结果(下面的第一个屏幕截图)。在其他浏览器中,它的行为符合预期(第二个屏幕截图)。有没有更好的方法来实现这一点,或者这个问题只出现在 Windows Chrome 中是否有原因?
更新:添加代码片段。
const svg = document.querySelector('.svg');
const ref = document.querySelector('.ref');
const outer = document.querySelector('.outer');
const refRect = ref.getBoundingClientRect();
console.log('.svg BoundingClientRect', svg.getBoundingClientRect());
console.log('.ref BoundingClientRect', refRect);
$(outer).css('top', refRect.top - window.scrollY)
$(outer).css('left', refRect.left - window.scrollX)
svg {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
}
.ref {
background: #ccffcc;
width: 100%;
height: 100%;
}
.outer {
border: 1px solid red;
width: 100px;
height: 100px;
position: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg class="svg" version="1.1" xmlns="http://www.w3.org/2000/svg">
<foreignObject x="18%" y="14%" width="100" height="100">
<div class="ref">This should be perfectly surrounded by a red border</div>
</foreignObject>
</svg>
<div class="outer"></div>