gpt4 book ai didi

javascript - 始终位于区域内的顶部 div

转载 作者:技术小花猫 更新时间:2023-10-29 11:39:26 25 4
gpt4 key购买 nike

我创建了一个总是在顶部的div

.visibleDiv, #topLeft
{
position: fixed;
width: 150px;
border: solid 1px #e1e1e1;
vertical-align: middle;
background: #ffdab9;
text-align: center;
}

#topLeft
{
top: 10px;
left: 10px;
}

然后我就这样显示了

<div id="topLeft">
Top Left
</div>

但我还有一个名为容器的 div。我希望 topLeft 留在该容器的左上角,而不是屏幕的左上角。我对 css 很陌生,一直在摸索如何实现这样的效果。

所以为了更清楚的解释我想尝试实现这个效果

______________
|Other things|
|____________|
________________________________
| TOP LEFT MESSAGE| |
|_________________| |
| |
| |
| CONTAINER DIV |
| |
| |

当你向下滚动时,我希望左上角像这样位于容器选项卡内屏幕的左上角

|__________________            |
| TOP LEFT MESSAGE| |
|_________________| |
| |
| |
| CONTAINER DIV |
| |
| |
|______________________________|

如果有人能给我指出正确的方向或告诉我如何通过解释实现这一目标,我将非常感激。提前感谢任何帮助或只是阅读这篇文章的人。

最佳答案

只需添加 position:relative 到您的容器元素即可。

查看此 fiddle

更新

jQuery在这里非常有用。您可以使用它轻松计算“容器”何时到达视口(viewport)顶部,然后将类重新分配给“topLeft”元素以修复它。

HTML

<div class="head">
Some Stuff
</div>
<div class="container">
<div id="topLeft">Top Left Stuff</div>
Container Stuff
</div>

CSS

.container
{

background-color:#FAA;
height:1000px;
}

#topLeft
{
width: 150px;
border: solid 1px #e1e1e1;
vertical-align: middle;
background: #ffdab9;
text-align: center;
}

.fixit
{
position:fixed;

top: 0px;
}

Javascript

<!-- Include jQuery Library -->
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<!-- Wire Up Our Magic -->
<script type='text/javascript'>
$(window).load(function(){
$(window).scroll(function () {
if(($(".container").position().top - $(window).scrollTop()) <= 0)
{
$("#topLeft").addClass("fixit");
}
else
{
$("#topLeft").removeClass("fixit");
}

});
});

</script>

查看实际效果 here

关于javascript - 始终位于区域内的顶部 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8620726/

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