我想創(chuàng)建一個有粘性的導(dǎo)航欄和側(cè)邊欄的頁面。只有內(nèi)容區(qū)不應(yīng)該是粘性的。
導(dǎo)航欄應(yīng)該有一個下拉按鈕。現(xiàn)在的問題是粘性邊欄與下拉菜單重疊。如果下拉菜單有多個項目,你不能點擊一個項目。
有沒有辦法強(qiáng)制下拉菜單覆蓋粘性邊欄?
var open = false;
function toggle() {
open = !open;
if (open) {
document.getElementById('menu').classList.add('visibile')
} else {
document.getElementById('menu').classList.remove('visibile')
}
}
.parent {
display: grid;
grid-template-areas: "navbar navbar" "sidebar content";
position: relative;
}
.navbar {
height: 50px;
background: #0f0;
grid-area: navbar;
position: sticky;
top: 0;
}
.menu {
display: none;
width: 300px;
height: 300px;
background: #00f;
position: absolute;
}
.visibile {
display: block !important;
}
.sidebar {
/* width: 200px; */
height: 100px;
background: #000;
grid-area: sidebar;
position: sticky;
top: 50px;
}
.content {
min-height: 1000px;
background-image: linear-gradient(red,orange,yellow,green,blue,indigo,violet);
grid-area: content;
}
<div class="parent">
<div class="navbar">
<button onclick="toggle()">Dropdown</button>
<div id="menu" class="menu"></div>
</div>
<div class="sidebar"></div>
<div class="content">
</div>
</div>
你要設(shè)置z-index:1;到導(dǎo)航條。了解有關(guān)z索引CSS屬性的更多信息。因此,導(dǎo)航條變成可點擊的。
請看下面的片段。
片段1:
var open = false;
function toggle() {
open = !open;
if (open) {
document.getElementById('menu').classList.add('visibile')
} else {
document.getElementById('menu').classList.remove('visibile')
}
}
/* Added */
const link = document.querySelector("a");
link.addEventListener("click", () => {
console.log("Clicked");
});
.parent {
display: grid;
grid-template-areas: "navbar navbar" "sidebar content";
position: relative;
}
.navbar {
height: 50px;
background: #0f0;
grid-area: navbar;
position: sticky;
top: 0;
z-index: 1; /* Added */
}
.menu {
display: none;
width: 300px;
height: 300px;
background: #00f;
position: absolute;
}
/* Added */
.menu a {
color: white;
}
.visibile {
display: block !important;
}
.sidebar {
height: 100px;
background: #000;
grid-area: sidebar;
position: sticky;
top: 50px;
}
.content {
min-height: 1000px;
background-image: linear-gradient(red, orange, yellow, green, blue, indigo, violet);
grid-area: content;
}
<div class="parent">
<div class="navbar">
<button onclick="toggle()">Dropdown</button>
<div id="menu" class="menu">
<a href="#">Click me</a>
</div>
</div>
<div class="sidebar"></div>
<div class="content"></div>
</div>