gpt4 book ai didi

html - 仅 CSS 位置 x : fixed

转载 作者:行者123 更新时间:2023-12-04 15:20:16 26 4
gpt4 key购买 nike

是否可以在没有 JavaScript 的情况下使元素在 x 轴上具有有效的 position: fixed,但在 y 轴上具有 position: absolute?有关使用 JavaScript 的示例,请参阅此代码段:

$(window).scroll(function(){
var $win = $(window);
$('#box1').css('top', 20 -$win.scrollTop());
$('#box2').css('left', 20 -$win.scrollLeft());
});
html, body {
width: 2000px;
height: 2000px;
}

.box {
width: 400px;
height: 80px;
background: gray;
position: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box1" class="box" style="left:20px;top:20px;">
My position-x is fixed but position-y is absolute.
</div>
<div id="box2" class="box" style="left:20px;top:120px;">
My position-x is absolute but position-y is fixed.
</div>
<div id="box3" class="box" style="left:20px;top:220px;">
Im positioned fixed on both axis.
</div>

最佳答案

您可以使用 margin-topposition: sticky。它会给你想要的结果。

$(window).scroll(function() {
var $win = $(window);
$('#box1').css('top', 20 - $win.scrollTop());
$('#box2').css('left', 20 - $win.scrollLeft());
});
html,
body {
width: 2000px;
height: 2000px;
}

.box {
width: 400px;
height: 80px;
background: gray;
position: fixed;
}

#box3 {
margin-top: 220px; /* use 'margin-top' instead of 'top' */
position: sticky;
left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box1" class="box" style="left:20px;top:20px;">
My position-x is fixed but position-y is absolute.
</div>
<div id="box2" class="box" style="left:20px;top:120px;">
My position-x is absolute but position-y is fixed.
</div>
<div id="box3" class="box">
Im positioned fixed on both axis.
</div>

关于html - 仅 CSS 位置 x : fixed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63466756/

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