查看“︁编程语言/getBoundingClientRect”︁的源代码
来自康健生活
←
编程语言/getBoundingClientRect
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== 引言 == == getBoundingClientRect == <blockquote><pre> Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。</pre></blockquote> {{Warning|很绕口的地方需要注意,有些属性是基于视窗,并不是基于网页整体大小}} === DOMRect === 这个对象是由该元素的 getClientRects() 方法返回的一组矩形的集合。 [[文件:GetBoundingClientRect.png|600px|getBoundingClientRect]] ==== bottom ==== 是距离视窗(浏览器标签窗口,并不是页面最顶部)的距离 == 计算误差 == 在 react 中使用 getBoundingClientRect 发现计算误差,现在有一个需求,有三个 DOM,分别是 body、点击按钮、弹出框。需要将弹出框的定位定在按钮的旁边,同时根据 body 限定右边界和下边界,当弹出框超出边界时,自动左移或上移。 [[文件: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 的宽度。 == 回流 == 如果 dom 插入 body 中,计算属性布局,然后设置定位脱离文档流,触发回流,重新计算属性布局{{Qm|那么丢失的 margin-top 为什么没有重新渲染出来}} 如果 先定位脱离文档流呢, 这里我们做一个假设,先 {{codetab|tabs=<tabs><tab name="html"><syntaxhighlight lang="html5"><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=, initial-scale="> <meta http-equiv="X-UA-Compatible" content=""> <title></title> </head> <body> <div style="height: 60px;margin-bottom: 40px; background: red;"></div> </body> </html> </syntaxhighlight></tab><tab name="css"><syntaxhighlight lang="css">.test{ margin-top: 40px; width: 100%; height: 40px; background: green; } </syntaxhighlight></tab><tab name="js"><syntaxhighlight lang="javascript">var dom = document.createElement('div'); setInterval(()=>{ dom.style.position = 'fixed' dom.className = 'test'; document.body.appendChild(dom) },3000) </syntaxhighlight></tab></tabs>}} <br> [[文件:固定定位触发回流时重新计算margin.gif|600px|无框|无|固定定位触发回流时重新计算margin]] <br> 我们可以看到当 div 插入文档中时,会发生<code>上下外边距</code>合并{{Qm|塌陷}}, == 其他 == 以上我们思考为什么会丢失 margin-top,接下来思考如果已经开始触发 BFC == 参考 == * https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
此页面嵌入的页面:
模板:Codetab
(
查看源代码
)
模板:Meta box
(
查看源代码
)
模板:Qm
(
查看源代码
)
模板:Warning
(
查看源代码
)
模板:Warning/style.css
(
查看源代码
)
返回
编程语言/getBoundingClientRect
。
导航菜单
康健生活
搜索
user-page
通知
user-interface-preferences
个人工具
登录
五一
多读书,多运动,多到远处走走,再看看不一样的世界。