![](/img/trans.png)
[英]How Do I Fix the Nav Bar So That the Menu is Removed when the person is not viewing the nav bar? | CSS / Javascript
[英]How do I use JavaScript so that only the certain nav bar gets clicked on is highlighted at a time?
所以在我的網站中,我有一個導航欄可以瀏覽我的頁面。 我為它編寫了 css 代碼,所以在懸停時,它變成了金色,下面會出現一個白條。 我想知道是否有我可以使用的腳本,以便當您單擊其中一個導航鏈接時,它會保持懸停狀態,並在單擊另一個導航鏈接時重置。 繼承人我的 CSS 代碼,所以你明白了:
.Home-link::after{ content: ''; width: 0%; height: 3px; background: white; display: block; transition: 1s; } .Home-link:hover::after{ width: 100%; color: gold; } .Home-link:hover{ color: gold; }
<section class="nav"> <div class="nav-links"> <a href="#TitlePage" class="Home-link">Home</a> <a href="#about" class="about-link">About</a> <a href="#Experience" class="Experience-link">Experience</a> </div> </section>
我可以用兩種方式解釋你的問題,所以我會盡量回答這兩種情況。
當您單擊其中一個導航鏈接時,它會保持懸停狀態,並在單擊另一個導航鏈接時重置
這告訴我您正在尋找:focus
(或其表親, :focus-within
;這取決於您的文檔結構)。
當用戶選項卡或點擊它們時,元素會得到關注。 跳出或單擊別處會移除焦點。
您可以組合選擇器,以便:hover
和:focus
做同樣的事情,就像這樣:
.Home-link:hover,
.Home-link:focus {
color: gold;
}
但是,如果您正在尋找更持久的解決方案——將您的導航欄項目標記為“這是您所在的頁面”,您需要將類似active
(或您喜歡的任何其他名稱)之類的類應用於正確的項目。
此類問題的解決方案在很大程度上取決於您的項目/框架。 在原生 JavaScript 中,您可以檢查當前位置( window.location.href
),並根據其內容,將active
類添加到特定的導航欄項目。
if (window.location.href.contains('/home')) {
document.getElementsByClassName('Home-link')[0]?.classList.add('active');
}
然后,在 CSS 中:
.Home-link:hover,
.Home-link.active {
color: gold;
}
你可以通過以下方式做到這一點。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
var links = $('.customcss').click(function () {
links.removeClass('CurrActive');
links.removeClass('a');
$(this).addClass('CurrActive');
});
});
</script>
<style>
.Home-link::after {
content: '';
width: 0%;
height: 3px;
background: white;
display: block;
transition: 1s;
}
.Home-link:hover::after {
width: 100%;
color: gold;
}
.Home-link:hover {
color: gold;
}
.CurrActive {
color: gold;
}
a:focus, a:hover {
color: gold;
outline: 0
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<section class="nav">
<div class="nav-links">
<a href="#TitlePage" class="Home-link customcss">Home</a>
<a href="#about" class="about-link customcss">About</a>
<a href="#Experience" class="Experience-link customcss">Experience</a>
</div>
</section>
</div>
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.