首页 > 解决方案 > JS、内联 CSS 和 getBoundingClientRect 之间的 style.top 不一致

问题描述

有人可以对这里发生的事情有所了解吗?

JS、内联 CSS 和 getBoundingClientRect

查看控制台,我看到三个明显不兼容的数字:在同一个元素 temp0 上(控制台中突出显示的那个,箭头指向的位置,它是一个星号),如果我检查style.top我得到一个值,检查内联 CSS第二个,并通过getBoundingClientRect.top三分之一。我错过了什么,或者可能是什么原因导致这样的事情?

html从上到下的结构是:一对导航栏,一个div占 30% viewport height,第二个div使用剩余的约 70%,分为三列bootstrap 4.5(尺寸 1-10-1)。

背景是:我不知道有多少问题和文章一直在阅读,试图解决我的代码中不断出现的看似愚蠢的对齐错误。

今晚我以为我在这个功能和详细的文章中找到了一些确定的东西,又过了两个小时无济于事。当我在控制台中看到这三个命令的结果时,我意识到我需要帮助:PI 非常感谢任何关于我遗漏的提示。

标签: javascripthtmlcssbootstrap-4

解决方案


我不确定您在页面中还做了什么,但看起来您尝试将元素设置style.top320.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>


推荐阅读