javascript - JS、内联 CSS 和 getBoundingClientRect 之间的 style.top 不一致
问题描述
有人可以对这里发生的事情有所了解吗?
查看控制台,我看到三个明显不兼容的数字:在同一个元素 temp0 上(控制台中突出显示的那个,箭头指向的位置,它是一个星号),如果我检查style.top
我得到一个值,检查内联 CSS第二个,并通过getBoundingClientRect.top
三分之一。我错过了什么,或者可能是什么原因导致这样的事情?
html
从上到下的结构是:一对导航栏,一个div
占 30% viewport height
,第二个div
使用剩余的约 70%,分为三列bootstrap 4.5
(尺寸 1-10-1)。
背景是:我不知道有多少问题和文章一直在阅读,试图解决我的代码中不断出现的看似愚蠢的对齐错误。
今晚我以为我在这个功能和详细的文章中找到了一些确定的东西,又过了两个小时无济于事。当我在控制台中看到这三个命令的结果时,我意识到我需要帮助:PI 非常感谢任何关于我遗漏的提示。
解决方案
我不确定您在页面中还做了什么,但看起来您尝试将元素设置style.top
为320.75px
,尽管控制台将其打印出来,但看起来内联样式实际上并未受到影响。
style.top
相当于内联样式(而不是CSS 中定义的任何内容)。请参见下面的示例。style.top
可能无法准确表示元素实际在屏幕上的位置。第一个内部元素具有默认值position: static
,因此即使很难,它也具有top
内联和 CSS 的集合,既不影响元素,但style.top
仍然显示100px
.
getBoundingClientRect()
总是相对于窗口。第一个内部元素实际上是距页面顶部 8px 的位置,这rect.top
表明。第二个内部元素有position: absolute
,因此它受到影响style.top
,它实际上距离页面顶部 250px。
console.log('inner1 rect.top: ' +inner1.getBoundingClientRect().top);
console.log('inner1 style.top: ' +inner1.style.top);
console.log('inner2 rect.top: ' +inner2.getBoundingClientRect().top);
console.log('inner2 style.top: ' +inner2.style.top);
#outer {
background: red;
display: block;
height: 400px;
width: 400px;
}
#inner1 {
background: yellow;
display: block;
height: 100px;
top: 5px;
width: 100px;
}
#inner2 {
background: blue;
display: block;
height: 100px;
top: 5px;
width: 100px;
}
<div id="outer">
<div id="inner1" style="top:100px;"></div>
<div id="inner2" style="position:absolute; top:250px;"></div>
</div>
推荐阅读
- mysql - 根据mysql中获得的点过滤等级
- .net - 在 F# 中正确使用带有指针的 P/invoke
- scala - 在模拟类中使用 var 时出现空指针异常
- regex - 正则表达式搜索给定单词带有额外空格的字符串
- json - RDF4J SPARQL 查询到 JSON
- revit-api - 行走 Autodesk Desktop Connector - BIM 360 和 360 Team 文件夹
- json - 从嵌套 JSON 在 Athena 中创建表
- pandas - 如何从 pandas 数据框创建数据块表?
- shell - shell 脚本中的 ${command_} 是什么
- fortran - 处理无限多态虚拟参数的单个元素时选择了错误的列