将已单击的菜单项标记为活动



所以我想知道如何使已点击的菜单项显示为'活动'/'突出显示',以便用户可以看到他们在哪个页面上?

我做了这个菜单栏。

/* Add a black background color to the top navigation */
.topnav_menu {
background-color: #333;
overflow: hidden;
display: flex;
align-items: center;
}

/* Style the links inside the navigation bar */
.topnav_menu a {
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
cursor: pointer;
}

/* Change the color of links on hover */
.topnav_menu a:hover,
.engine_dropdown:hover .engine_dropbtn {
background-color: #ebebeb;
color: black;
}
<div class="topnav_menu">
<!-- # will be removed for enable redirect -->
<a href="#profile">Profile</a>
<a href="#index">Test Runs</a>
<a href="#dashboard">Dashboard</a>
<a href="#dbOperations">TRT Tools</a>
</div>

项目被点击后,它应该高亮显示。

编辑

所以我创造了一个解决方案,但这是最好的方法吗?

创建这个函数来检查在哪个页面上,然后如果我在那个页面上,我会将类设置为active

function active($currect_page){
$url = basename(getcwd())."/".str_replace(".php", "", basename($_SERVER['PHP_SELF'])); // If filename is just "name" or "name.php"
// Also checks which directory the file is in, to avoid highlighting multiple menu items with same name
// $currect_page == $url :: parentFolder/fileName == parentFolder/fileName (without .php here)
if($currect_page == $url || $currect_page == basename(getcwd())."/".basename($_SERVER['PHP_SELF'])){
echo 'active'; // class name in css
}
}
<div class="topnav_menu">
<a href="profile" class="<?php active('Test/profile'); ?>"><div id="imgDiv"></div></a>
<a href="index" class="<?php active('Test/index'); ?>">Test Runs</a>
<a href="dashboard" class="<?php active('Test/dashboard'); ?>">Dashboard</a>
<a href="dbOperations" class="<?php active('Test/dbOperations'); ?>">TRT Tools</a>
</div>

active类看起来像这样

/* Active menu item */
.topnav_menu a.active,
.topnav_menu a:focus {
/* When a-tags inside this class has been clicked */
background-color: #ffffff;
color: black;
}

基于你如何写HTML,下面的js将解决这个问题。

//JS
let a = document.querySelectorAll('a')
for(let i =0; i< a.length; i++){
a[i].onclick = function(){
a.forEach(function(item){
item.classList.remove("active");
});
this.classList.add("active");
}
}

最新更新