Jquery 当前页面链接样式

Jquery current page link styling

本文关键字:样式 链接 当前页 Jquery      更新时间:2023-09-26

嗨,我正在尝试使用户所在页面的链接样式与导航栏中的其他链接不同。

<script src="jquery-1.11.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $(function() {
                $('.Global_Nav li').each(function() {
                    var href = $(this).find('a').attr('href');
                    if ($(this).attr('href')  ===  window.location.pathname) {
                        $(this).addClass('current');
                    }
                });
            }); 
        })
    </script>

这是我发现的jquery,它似乎是对我想要实现的目标最有意义的代码。

.Global_Nav li{
    display: inline-block;
    text-align: center;
    height: 35px;
    padding-right: 14px;
    padding-left: 14px;
    list-style: none;
    border-left: 1px solid white;
    line-height: 35px;
    font-size: 22px;
    color: white;
    
    
}
.Global_Nav li.current{
    display: inline-block;
    text-align: center;
    height: 35px;
    padding-right: 14px;
    padding-left: 14px;
    list-style: none;
    border-left: 1px solid white;
    line-height: 35px;
    font-size: 22px;
    color: #B8B8C7;
    text-decoration: underline;
}

上面的 CSS 是链接应该事先设置样式以及当前页面时的样式。下面是导航栏的 HTML。

<nav class="Global_Nav">
            <ul id="Global_links">
                <li><a href="HomeTemplate.html">Home</a></li>
                <li><a href="NewsTemplate.html">News</a></li>
                <li><a href="MultimediaTemplate.html">Multimedia</a></li>
                <li><a href="SocialTemplate.html">Social</a></li>
                
            </ul>
        </nav>

提前感谢您的帮助。

使用location.href。

这个帖子网址使用window.location.pathname:"/questions/28988304/jquery-current-page-link-styleing"

这个帖子网址使用location.href:"Jquery当前页面链接样式"

使用 window.location.href 而不是 window.location.pathname

if ( $(this).attr('href') == window.location.href ) {       
    $(this).addClass('current');
}