gpt4 book ai didi

jquery - 相对于容器的响应式固定位置元素

转载 作者:行者123 更新时间:2023-11-28 01:42:09 26 4
gpt4 key购买 nike

我希望元素在滚动时保持其位置,但与容器元素的高度一样长。

我用这个例子找到了一个很好的答案:http://jsfiddle.net/R8bUQ/

但我想知道是否有一种方法可以在不指定容器元素高度的情况下使其响应。

这是失败的尝试...该元素一直显示在容器外!

$parent = $('.container');
$elem = $parent.find('div');

$(window).scroll(function(){
$elem.css('top', $(window).scrollTop());
}).trigger('scroll');
div {
min-height: 200px;
margin-left: 60px;
background: #ccc;
width: 300px;
}
div.container {
margin-top: 80px;
position: relative;
}
div .element {
min-height: 20px;
width: 100%;
background: #0f0;
position: absolute;
margin: 0;
top: 0;
left: 0;
}
div.outer-div {
min-height: 650px;
margin-top: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="element"></div>
<p>Another content inside container</p>
</div>
<div class="outer-div">
Another outer content. Element should not show over this div.
</div>

最佳答案

您可以通过在 js 代码中添加条件来检查内部元素是否超出父级来实现这一点。

$parent = $('.container');
$elem = $parent.find('.element');
$(window).scroll(function() {
if (($(window).scrollTop() + $elem.height()) < ($parent.offset().top + $parent.height())) {
$elem.css('top', $(window).scrollTop());
}
}).trigger('scroll');
div {
min-height: 200px;
margin-left: 60px;
background: #ccc;
width: 300px;
}

div.container {
position: relative;
}

div .element {
min-height: 20px;
width: 100%;
background: #0f0;
position: absolute;
margin: 0;
top: 0;
left: 0;
}

div.outer-div {
min-height: 650px;
margin-top: 40px;
}
body,p { margin: 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="element"></div>
<p>Another content inside container</p>
</div>
<div class="outer-div">
Another outer content. Element should not show over this div.
</div>

关于jquery - 相对于容器的响应式固定位置元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50381063/

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