Issue
However, if other text is added to the URL, active is lost.
Even if other text is added to the url, I would like to keep it active if it contains a specific “data-target”.
For example, if the original link is "link/sub01.html" but changes to "link/sub01.html&page=2", the style is lost.
Even if the text "&page=2" is added, I want active to always be added if "sub01" is in the url.
But I'm not familiar with the script yet, so I don't know where to fix it. Please help me. I didn't speak English, so I used a translator.
So the sentence may not be smooth. Sorry!
$(document).ready(function() {
var url = window.location;
$('#Nav .Cate li a[href="' + 'data-target' + '"]').parent().addClass('active');
$('#Nav .Cate li a').filter(function() {
return this.href == url;
}).parent().addClass('active').parent().parent().addClass('active');
});
.Cate {
position: relative;
}
.Cate li {
position: relative;
display: inline-block;
width: 180px;
height: 34px;
float: left;
line-height: 34px;
text-align: center;
border: 1px solid #333;
border-bottom: 0;
border-radius: 15px 15px 0 0;
box-sizing: border-box;
overflow: hidden;
background: rgba(51, 51, 51, 0);
transition: all .35s;
}
.Cate li a {
display: block;
text-decoration: none;
background: rgba(51, 51, 51, 0);
transition: all .35s;
}
.Cate li:hover {
background: rgba(51, 51, 51, 1);
}
.Cate li:hover a {
color: #fff;
}
.Cate li.active {
background: rgba(51, 51, 51, 1);
}
.Cate li.active a {
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Nav">
<ul class="Cate">
<li data-target="index"><a href="index.html">MAIN</a></li>
<li data-target="sub01"><a href="sub01.html">SUB01</a></li>
<li data-target="sub02"><a href="sub02.html">SUB02</a></li>
</ul>
</div>
Solution
You need to make a slight change in your code to get the exact data-target
from the URL and then make the corresponding <li>
active
$(document).ready(function() {
var urlArr = window.location.pathname.split('/');
var dataTarget = urlArr[urlArr.length - 1];
$('.Cate li a[href="' + dataTarget + '"]').parent().addClass('active');
//rest code will be as it is
});
Answered By - Death-is-the-real-truth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.