gpt4 book ai didi

javascript - 如何将元素保持在视口(viewport)中?

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:22 25 4
gpt4 key购买 nike

我有一个 html 元素,它在单击按钮时显示。这有点像弹出窗口。我想检查它是否在浏览器的 ViewPort 中,然后将它放在 ViewPort 中。是否有实现该目标的正确方法?

目前我正在检查 ViewPort 的高度并将其与元素将附加到的点进行比较。所以我做了这样的事情:

If(window.innerHeight > yPointWhereElementIsAttachedTo + heightOfElement) //attach element; 

但是正确的做法是什么?

最佳答案

这可以通过在具有定位功能的元素上使用 position: fixed; 来实现。

例如:

.fixed {
position: fixed;
width: 300px;
height: 100px;
background: red;
left: 10px;
top: 40px;
}

.wrapper {
min-height: 4000px;
}
<div class="wrapper">
<div class="fixed">
I am fixed in the viewport
</div>
</div>

关于javascript - 如何将元素保持在视口(viewport)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57322311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com