Javascript 我正在做导航条。我想使用jscript向nav元素添加一个活动类。具体取决于url
我想我应该使用window.location.pathname来获取url。并存储在名为page_name的变量中 然后我想说,如果windows.location.pathname在url栏中,那么将活动类添加到我的 这是我到目前为止所拥有的。让我知道我需要改变什么Javascript 我正在做导航条。我想使用jscript向nav元素添加一个活动类。具体取决于url,javascript,uinavigationbar,Javascript,Uinavigationbar,我想我应该使用window.location.pathname来获取url。并存储在名为page_name的变量中 然后我想说,如果windows.location.pathname在url栏中,那么将活动类添加到我的 这是我到目前为止所拥有的。让我知道我需要改变什么 <div class="nav-collapse"> <ul id="nav" class="nav"> <li id="home"><a href="home_page.ph
<div class="nav-collapse">
<ul id="nav" class="nav">
<li id="home"><a href="home_page.php">Home</a></li>
<li id="watch"><a href="watch.php">Watch</a></li>
</ul>
</div>
如果您询问脚本为什么不工作,那么我假设您的jquery选择器是错误的。试试这个: nav.js: common.css:
.active {
background-color: red;
}
{home_page,watch}.html:
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" type="text/css" href="common.css">
<title></title>
</head>
<body>
<div class="nav-collapse">
<ul id="nav" class="nav">
<li id="home">
<a href="home_page.html">Home</a>
</li>
<li id="watch">
<a href="watch.html">Watch</a>
</li>
</ul>
</div>
<script src="jquery.js" type="text/javascript"></script>
<script src="nav.js" type="text/javascript"></script>
</body>
</html>
这也不行。当我使用你的代码时。它不会将类添加到。另外,我更喜欢在li而不是a上换课。因为我已经为liI设置了css活动类,所以增强了我的示例。请考虑我选择一个带有正确的HERF的标签,然后我导航到父Li元素。尝试$A[HeRF$=’+PaGyNoNe++’]。
.active {
background-color: red;
}
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" type="text/css" href="common.css">
<title></title>
</head>
<body>
<div class="nav-collapse">
<ul id="nav" class="nav">
<li id="home">
<a href="home_page.html">Home</a>
</li>
<li id="watch">
<a href="watch.html">Watch</a>
</li>
</ul>
</div>
<script src="jquery.js" type="text/javascript"></script>
<script src="nav.js" type="text/javascript"></script>
</body>
</html>