简体   繁体   English

使用javascript更改所选锚标记文本的颜色

[英]change color of selected anchor tag text with javascript

i am trying to create a navigation menu as shown below. 我正在尝试创建如下所示的导航菜单。 how do i get my javascript to change the color of selected anchor tag menu. 我如何获取我的JavaScript来更改所选锚标签菜单的颜色。

HTML 的HTML

<script type="text/javascript">
$(function() {
       $("#menu ul li a").click(function() {
       // remove classes from all
       $("#menu ul li a").removeClass("active");
       // add class to the one we clicked
       $(this).addClass("active");
      });
   });
</script>

<div id="menu">
   <ul>
        <li><a href="index.html" class="active">home</a></li>
        <li><a href="about.html">about</a></li>
        <li><a href="portfolio.html">portfolio</a></li>
        <li><a href="contact.html">contact</a></li>
    </ul>
</div>

CSS 的CSS

#menu ul li a{background: -webkit-gradient(linear, left top, left bottom, from(#c5c5c5), to(#fff));;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;}

#menu ul li a:hover {
    background: -webkit-linear-gradient(top, #009ec5 0%, #005890 50%, #41d2fc 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
    }

#menu ul li a.active {
    background: -webkit-linear-gradient(top, #009ec5 0%, #005890 50%, #41d2fc 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
$('#menu ul li a').click(function(){

    $('#menu ul li a').removeClass('active');
    $(this).addClass('active');
});

By the looks of it you aren't preventing going to a new page when your anchors are clicked. 从外观上看,当您单击锚点时,您不会阻止进入新页面。 So I'm assuming that you'd just like to apply the class to the link corresponding to the page your currently on. 因此,我假设您只是想将该类应用于与您当前所在页面相对应的链接。

You don't need a click() event handler for this. 您不需要为此的click()事件处理程序。 You need to use the window.location.href to determine which page it is your on. 您需要使用window.location.href来确定您所在的页面。 Remove the class from the default link and then add it to that with a href attribute matching the window's href . 从默认链接中删除该类,然后使用与窗口的href匹配的href属性将其添加到该类中。 Something like the following will do: 如下所示:

$(function() {
    var page = window.location.href.split('/');
    page = page[page.length-1];
    $("#menu ul li a").removeClass("active").filter('[href="'+page+'"]').addClass('active');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM