Javascript 活动菜单突出显示 CSS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10646775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:20:07  来源:igfitidea点击:

Active Menu Highlight CSS

javascripthtmljquerycss

提问by justin

I want to highlight the current menu you have click. I'm using CSS, but it is now working.

我想突出显示您单击的当前菜单。我正在使用 CSS,但它现在正在工作。

here is my css code:

这是我的 css 代码:

#sub-header ul li:hover{ background-color: #000;}
#sub-header ul li:hover a{ color: #fff; }
#sub-header ul li.active{ background-color: #000; }
#sub-header ul li.active a{ color: #fff; }

here is my html:

这是我的 html:

<div id="sub-header">
    <ul>
        <li> <a href="index.php">Home</a> </li>
        <li> <a href="contact.php">Contact Us</a> </li>
        <li> <a href="about.php">About Us</a> </li>
    </ul>
</div>

This is what I like when I hover and if the menu is active

这是我在悬停和菜单处于活动状态时喜欢的

This is what I like when I hover and if the menu is active

这是我在悬停和菜单处于活动状态时喜欢的

Hover is okay, The problem is when I after click the menu the black ground is not display

悬停没问题,问题是当我点击菜单后,黑地不显示



@Jonathan, I have already solve it and it is more simply than what you have gave.

@Jonathan,我已经解决了它,它比你给出的更简单。

this is my answer:

这是我的回答:

$(function(){
    // this will get the full URL at the address bar
    var url = window.location.href; 

    // passes on every "a" tag 
    $("#sub-header a").each(function() {
            // checks if its the same on the address bar
        if(url == (this.href)) { 
            $(this).closest("li").addClass("active");
        }
    });
});

then on my css file:

然后在我的 css 文件上:

.active { background-color: #000; }
/* to override the existing css for "a" tag */
#sub-header .active a{ color: #fff; }

回答by Sampson

Add a class to the body of each page:

在每个页面的正文中添加一个类:

<body class="home">

Or if you're on the contact page:

或者,如果您在联系页面上:

<body class="contact">

Then take this into consideration when you're creating your styles:

然后在创建样式时考虑到这一点:

#sub-header ul li:hover,
body.home li.home,
body.contact li.contact { background-color: #000;}

#sub-header ul li:hover a,
body.home li.home a,
body.contact li.contact a { color: #fff; }

Lastly, apply class names to your list items:

最后,将类名应用于您的列表项:

<ul>
  <li class="home"><a href="index.php">Home</a></li>
  <li class="contact"><a href="contact.php">Contact Us</a></li>
  <li class="about"><a href="about.php">About Us</a></li>
</ul>

This point, whenever you're on the body.homepage, your li.home alink will have default styling indicating it is the current page.

这一点,无论何时您在body.home页面上,您的li.home a链接都会具有默认样式,表明它是当前页面。

回答by Mareno

Answer: You need CSS for “current” link here is tut.

答:这里的“当前”链接需要 CSS。

Description of jQuery menu nav

jQuery 菜单导航说明

Sample : One of meny solution

示例:许多解决方案之一

Its working for me

它为我工作

回答by bhavik kumar

add simply way

添加简单的方式

<div id='cssmenu'>
<ul>
<li class=''><a href='1.html'><span>1</span></a></li>
<li class=''><a href='2.html'><span>2</span></a></li>
<li class='' style="float:right;"><a href='3.html'><span>3</span></a></li>
</ul>
</div>

$("document").ready(function(){
$(function() {
$('.cssmenu a[href="' + location.pathname.split("/")[location.pathname.split("/").length-1] + '"]').parent().addClass('active');
});

});

回答by vish0910

As the given tag to this question is CSS, I will provide the way I accomplished it.

由于这个问题的给定标签是CSS,我将提供我完成它的方式。

  1. Create a class in the .css file.

    a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

  2. Nav-bar will be like:

    • Home
    • Contact Us
    • About Us
  1. 在 .css 文件中创建一个类。

    a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

  2. 导航栏将如下所示:

    • 联系我们
    • 关于我们

NOTE:If you are already setting the style for all Nav-Bar elements using a class, you can cascade the special-case class we created with a white-spaceafter the generic class in the html-tag.

Example:Here, I was already importing my style from a class called 'navList'I created for all list-items . But the special-case styling-attributes are part of class 'activePage'

注意:如果您已经使用一个类为所有 Nav-Bar 元素设置了样式,您可以在 html-tag 中的泛型类之后使用空格级联我们创建的特殊情况类。

示例:在这里,我已经从我为所有 list-items 创建的名为'navList'的类中导入了我的样式。但是特殊情况的样式属性是“activePage”一部分

.CSS file:

.CSS 文件:

a.navList{text-decoration: none; color: gray;}
a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

.HTML file:

.HTML 文件:

<div id="sub-header">
    <ul>
        <li> <a href="index.php" class= "navList activePage" >Home</a> </li>
        <li> <a href="contact.php" class= "navList">Contact Us</a> </li>
        <li> <a href="about.php" class= "navList">About Us</a> </li>
    </ul>
</div>

Look how I've cascaded one class-name behind other.

看看我是如何将一个类名级联到另一个之后的。

回答by hamid azhdari

Maybe it is very very bad way and just for lazy person but I decided to say it.

也许这是非常非常糟糕的方式,只是为了懒惰的人,但我决定说出来。

I used PHP and bootstrap and fontawsome too

我也使用了 PHP 和 bootstrap 以及 fontawsome

for simple I have 2 pages: 1.index and 2.create-user

简单来说,我有 2 个页面:1.index 和 2.create-user

put this code above your code

将此代码放在您的代码上方

<?php
$name=basename($_SERVER["REQUEST_URI"]);
$name=str_replace(".php","",$name);
switch ($name) {
    case "create-user":
        $a = 2;
        break;
    case "index":
        $a = 1;
        break;
    default:
        $a=1;
}
?>

and in menu you add <?php if($a==1){echo "active";} ?>in class for menu1 and for menu2 you add <?php if($a==2){echo "active";} ?>

并在菜单<?php if($a==1){echo "active";} ?>中为 menu1添加类,为 menu2 添加<?php if($a==2){echo "active";} ?>

<ul id="menu" class="navbar-nav  flex-column text-right mt-3 p-1">
                        <li class="nav-item mb-2">
                            <a href="index.php" class="nav-link text-white customlihamid <?php if($a==1){echo "active";} ?>"><i
                                        class="fas fa-home fa-lg text-light ml-3"></i>dashbord</a>
                        </li>
                        <li class="nav-item mb-2">
                            <a href="#" href="javascript:" data-parent="#menu" data-toggle="collapse"
                               class="accordion-toggle nav-link text-white customlihamid <?php if($a==2){echo "active";} ?>" data-target="#tickets">
                                <i class="fas fa-user fa-lg text-light ml-3"></i>manage users
                                <span class="float-left"><i class="fas fa-angle-down"></i></span>
                            </a>

                            <ul class="collapse list-unstyled mt-2 mr-1 pr-2" id="tickets">
                                <li class="nav-item mb-2">
                                    <a href="create-user.php" class="nav-link text-white customlihamid"><i class="fas fa-user-plus fa-lg text-light ml-3"></i>add user</a>
                                </li>

                                <li class="nav-item mb-2">
                                    <a href="#" class="nav-link text-white customlihamid"><i class="fas fa-user-times fa-lg text-light ml-3"></i>delete user</a>
                                </li>

                            </ul>
                        </li>

                    </ul>

and add in css

并添加 css

.customlihamid {
    transition: all .4s;
}

.customlihamid:hover {
    background-color: #8a8a8a;
    border-radius: 5px;
    color: #00cc99;
}
.nav-item > .nav-link.active  {
    background-color: #00cc99;
    border-radius: 7px;
    box-shadow: 5px 7px 10px #111;
    transition: all .3s;
}
.nav-item > .nav-link.active:hover  {
    background-color: #8eccc1;
    border-radius: 7px;
    box-shadow: 5px 7px 20px #111;
    transform: translateY(-1px);
}

and in js add

并在js中添加

$(document).ready(function () {
   $('.navbar-nav .nav-link').click(function(){
      $('.navbar-nav .nav-link').removeClass('active');
      $(this).addClass('active');
   })
});

first check your work without js code to understand js code for what

首先在没有js代码的情况下检查你的工作以了解js代码是什么

回答by dgknca

Let's say we have a menu like this:

假设我们有一个这样的菜单:

<div class="menu">
  <a href="link1.html">Link 1</a>
  <a href="link2.html">Link 2</a>
  <a href="link3.html">Link 3</a>
  <a href="link4.html">Link 4</a>
</div>

Let our current url be https://demosite.com/link1.html

让我们当前的网址是 https://demosite.com/link1.html

With the following function we can add the active class to which menu's href is in our url.

使用以下函数,我们可以添加菜单的 href 在我们的 url 中的活动类。

let currentURL = window.location.href;

document.querySelectorAll(".menu a").forEach(p => {
  if(currentURL.indexOf(p.getAttribute("href")) !== -1){
    p.classList.add("active");
  }
})

回答by swift

First, give all your links a unique id and make a css class called active:

首先,给你的所有链接一个唯一的 id 并创建一个名为 active 的 css 类:

<ul>
    <li><a id="link1" href="#/...">link 1</a></li>
    <li><a id="link2" href="#/...">link 2</a></li>
</ul>

CSS:

CSS:

.active {
    font-weight: bold;
}

Jquery version:

jQuery 版本:

function setActiveLink(setActive){
    if ($("a").hasClass('active'))
        $("a").removeClass('active');
    if (setActive)
        $("#"+setActive).addClass('active');
}

$(function() {
    $("a").click(function() {
        setActiveLink(this.id);
    });
});

Vanilla javascript version:

香草 javascript 版本:

In order to prevent selecting too many links with document.querySelectorAll, give the parent element an id called menuLinks. Add an onClick handler on the links.

为了防止选择过多的链接document.querySelectorAll,给父元素一个名为 menuLinks 的 id。在链接上添加一个 onClick 处理程序。

<ul id="menuLinks">
    <li><a id="link1" href="#/..." onClick="setActiveLink(this.id);">link 1</a></li>
    <li><a id="link2" href="#/..." onClick="setActiveLink(this.id);">link 2</a></li>
</ul>

Code:

代码:

function setActiveLink(setActive){
    var links = document.querySelectorAll("#menuLinks a");
    Array.prototype.map.call(links, function(e) {
        e.className = "";
        if (e.id == setActive)
            e.className = "active";
    })
}

回答by S Harish Morampudi

You should refer to the current element and not all elements matching your selector.

您应该引用当前元素而不是所有与您的选择器匹配的元素。

$("#mainMenu td").click(function() {
$(this).css('background-color', '#EDEDED');

});

});

I′d also recommend you to use CSS classes instead of setting the CSS properties this way.

我还建议您使用 CSS 类而不是这样设置 CSS 属性。

That would be something like;

那会是这样的;

$("#mainMenu td").click(function() {
$(this).addClass('selected');

});

});

together with;

和...一起;

#mainMenu td.selected {

background-color: #EDEDED; }

背景颜色:#EDEDED;}

回答by Amee

Try this (Do copy and paste):

试试这个(复制和粘贴):

Test.html:-

测试.html:-

<html>
 <link rel="stylesheet" type="text/css" href="style.css">
 <a class="fruit" href="#">Home</a></span>
 <a class="fruit"  href="#">About</a></span>
 <a class="fruit"  href="#">Contact</a></span>
</html>

style.css:-

style.css:-

a:link{
 color:blue;
}

a:visited{
 color:purple;
}

a:hover{
 color:orange;
}
a:focus{
color:green;
}

a:active{
 color:red;
}

a:active{
 color:yellow;
}

回答by Gene Bo

Another variation with a simple 2-line listener

带有简单 2 行侦听器的另一种变体

$( ".menu_button" ).click(function() {

    $( ".menu_button" ).removeClass('menu_button_highlight');
    $(this).addClass('menu_button_highlight');
});

=====

======

    <a class='menu_button' href='#admin'>Admin</a>
    <br/>

    <a class='menu_button' href='#user_manager'>User Manager</a>
    <br/>

    <a class='menu_button' href='#invite_codes'>Invite Codes</a>

====

====

.menu_button {

    padding: 0 5px;
}

.menu_button_highlight {

    background: #ffe94c;
}