使用JS实现导航切换时高亮显示的示例讲解
(编辑:jimmy 日期: 2025/10/26 浏览:3 次 )
index.html代码内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>导航高亮显示</title>
<style type="text/css">
body{
font-size:20px;
}
.nav{
list-style-type: none;
margin:0;
padding:0;
}
.clear:after{
content:'/20';
display:block;
clear:both;
height:0;
visibility: hidden;
}
.nav li{
float:left;
background:#B1DFF5;
margin-right:1px;
color:#fff;
}
.nav li a{
display:block;
height:45px;
width:120px;
line-height:45px;
text-align:center;
text-decoration:none;
}
.active{
background:#28b1f3;
font-weight:bold;
}
</style>
</head>
<body>
<ul class="nav clear" id="nav">
<li><a href="index.html" rel="external nofollow" rel="external nofollow" >首页</a></li>
<li><a href="1.html" rel="external nofollow" rel="external nofollow" >栏目一</a></li>
<li><a href="2.html" rel="external nofollow" rel="external nofollow" >栏目二</a></li>
<li><a href="3.html" rel="external nofollow" rel="external nofollow" >栏目三</a></li>
</ul>
</body>
<script type="text/javascript" src="/UploadFiles/2021-04-02/jquery-1.7.min.js">
1.html代码内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>栏目一</title>
<style type="text/css">
body{
font-size:20px;
}
.nav{
list-style-type: none;
margin:0;
padding:0;
}
.clear:after{
content:'/20';
display:block;
clear:both;
height:0;
visibility: hidden;
}
.nav li{
float:left;
background:#B1DFF5;
margin-right:1px;
color:#fff;
}
.nav li a{
display:block;
height:45px;
width:120px;
line-height:45px;
text-align:center;
text-decoration:none;
}
.active{
background:#28b1f3;
font-weight:bold;
}
</style>
</head>
<body>
<ul class="nav clear" id="nav">
<li><a href="index.html" rel="external nofollow" rel="external nofollow" >首页</a></li>
<li><a href="1.html" rel="external nofollow" rel="external nofollow" >栏目一</a></li>
<li><a href="2.html" rel="external nofollow" rel="external nofollow" >栏目二</a></li>
<li><a href="3.html" rel="external nofollow" rel="external nofollow" >栏目三</a></li>
</ul>
<h1>栏目一</h1>
</body>
<script type="text/javascript" src="/UploadFiles/2021-04-02/jquery-1.7.min.js">
效果图
注意:
1、 location.href 用于获取当前页面的url
2、 当前页面应该保存为index.html
3、 indexOf 用于检索当前url中是否存在a中对应的href
4、 每个html中都拥有相同的导航结构
5、 eq(index/-index) 获取当前链式操作中第N个JQuery对象,返回JQquery对象,当参数大于等于0时为正向选取,比如0代表第一个,1代表第二个。当参数为负数时为反向选取,比如-1代表倒数第一个。
拓展知识:js实现导航菜单点击切换选中时高亮状态方法
通过 include() 或require() 函数,您可以在服务器执行 PHP 文件之前在该文件中插入一个文件的内容。
除了它们处理错误的方式不同之外,这两个函数在其他方面都是相同的。
include() 函数会生成一个警告(但是脚本会继续执行),
而 require() 函数会生成一个致命错误(fatal error)(在错误发生后脚本会停止执行)。
这两个函数用于创建可在多个页面重复使用的函数、页眉、页脚或元素。
这会为开发者节省大量的时间。
这意味着您可以创建供所有网页引用的标准页眉或菜单文件。当页眉需要更新时,您只更新一个包含文件就可以了,或者当您向网站添加一张新页面时,仅仅需要修改一下菜单文件(而不是更新所有网页中的链接)。
这时就会出现这样的问题:导航高亮应该怎样处理?
公共代码提出后就不可能在每个页面的导航栏目后加class=“active”属性进行修改,这时就需要使用javascript来搞定。
代码如下:
上一篇:jQuery实现鼠标移到某个对象时弹出显示层功能
下一篇:Vue 菜单栏点击切换单个class(高亮)的方法
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。

