编程语言/getBoundingClientRect:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
第17行: 第17行:
[[文件:GetBoundingClientRect 1.jpg|300px|无框|无|GetBoundingClientRect 1]]
[[文件:GetBoundingClientRect 1.jpg|300px|无框|无|GetBoundingClientRect 1]]


在代码结构中
在代码结构中,需要将影响 getBoundingClientRect 获取页面实际渲染尺寸的代码,放在计算相关代码上面。
<syntaxhighlight lang="javascript" highlight="3">
    // kangkk: 涉及到影响 ref 长宽高及其坐标属性的 css 样式更改,应该放到最前面进行。
    // 否则 getBoundingClientRect 获取不到准确值
    root.current.style.position = container === document.body ? 'fixed' : 'absolute';
    root.current.className = 'trigger_ref_box'
    root.current.style.zIndex = 9999;
    ...
    const {x, y, height, bottom: triggerRefBottom, right: triggerRefRight} = triggerRef.current.getBoundingClientRect();
    const {x: cx, y: cy, bottom: containerBottom, right: containerRight} = container.getBoundingClientRect();
    ...
    root.current.style.top = offsetTop + 'px';
    root.current.style.left = offsetLeft + 'px';</syntaxhighlight>
 
不然会出现 getBoundingClientRect 计算误差,比如如下:
 
[[文件:GetBoundingClientRect 2.jpg|400px|无框|无|GetBoundingClientRect 2]]
 
在此示例中 getBoundingClientRect 计算高度缺少了一个 margin-top,同时宽度变成了 body 的宽度。


== 参考 ==
== 参考 ==
* https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
* https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect