我正在尝试让粘性父级的子绝对元素向下滚动[[not(本质上是跟随父级粘性)。
问题是标题元素在topbar
元素下面。当打开抽屉而不滚动时,它位于顶部栏的下方,这是有道理的,因为绝对指示它遵循父对象的相对位置。 我正在尝试将抽屉坐在top:0px
(相对于固定位置)上,位于屏幕的顶部,与顶部栏重叠。将元素从top:0px
移至top:-20px
无效,因为抽屉中的内容会被截断。
我想到的一种解决方案是,通过元素滚动调整元素的top
值以给出这种错觉,但是就资源而言,这似乎有些极端。
第二种解决方法是将抽屉与父抽屉解耦,但是...
..实际上实际上是一个复杂得多的头文件/功能,其中包含过多的耦合和移动部件(我没有做到)。由于元素的父/子依赖性,更改时非常微妙,否则将抽屉作为其自身的元素将是最简单的解决方案。
这里是目前如何运作的一个小例子:
$("#toggle").click(function() {
$("#drawer").toggle("open");
})
#wrapper {display:flex; flex-direction:column}
#topbar {
background-color: red;
height: 20px;
}
#header {
position: sticky;
z-index: 5;
top:0;
background-color: blue;
height :40px;
}
#drawer {
position:absolute;
height: 100vh;
top:0px;
right: 10px;
background-color:yellow;
}
#page {
height:900px;
}
.open {
right:50vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="topbar">top bar</div>
<div id="header">
<div id="header_inner">
<button id="toggle"> Drawer Toggle</button>
</div>
<div id="drawer" >
Drawer Content
</div>
</div>
<div id="page"> Page Content <div>
我添加了一条规则来避免HTML和BODY的边距,因为如果有边距或填充,则需要将它们添加到计算中。
$(document).on( 'scroll', function(){
let scroll = $(document).scrollTop();
let diff = 20 - scroll;
if(diff > 20) {
$("#drawer").css('top', 0);
} else if(diff >= 0) {
$("#drawer").css('top', '-' + diff + 'px');
}
});
$("#toggle").click(function() {
$("#drawer").toggle("open");
});
html, body {
margin:0;
padding:0;
}
#wrapper {display:flex; flex-direction:column}
#topbar {
background-color: red;
height: 20px;
}
#header {
position: sticky;
z-index: 5;
top:0;
background-color: blue;
height :40px;
}
#drawer {
position:absolute;
height: 100vh;
top:-20px;
right: 10px;
background-color:yellow;
}
#page {
height:900px;
}
.open {
right:50vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="topbar">top bar</div>
<div id="header">
<div id="header_inner">
<button id="toggle"> Drawer Toggle</button>
</div>
<div id="drawer" >
Drawer Content
</div>
</div>
<div id="page"> Page Content <div>