如何根据我所使用的路径将div类添加到div中,包括如果我有#在其中它不应该发生?
<div class="popup">
<ul>
<li><a href="#vs">Example 1</a></li>
<li><a href="#bod">Example 2</a></li>
<li><a href="#ptf">Example 3</a></li>
</ul>
</div><!-- popup -->
<!-- how would I add the class addMe with javascript depending on the site path? It has to work with # -->
示例index.html
答案 0 :(得分:5)
jQuery(function($){
switch(window.location.hash){
case "vs": $(".popup").addClass("class1"); break;
case "bod": $(".popup").addClass("class2"); break;
case "ptf": $(".popup").addClass("class3"); break;
}
});
答案 1 :(得分:0)
这些都不适合我。这有效:
<script type="text/javascript">
jQuery(document).ready(function($){
// Get current url
// Select an a element that has the matching href and apply a class of 'active'. Also prepend a - to the content of the link
var url = window.location.href;
$('.menu a[href="'+url+'"]').addClass('active');
});
</script>
菜单结构:
<div class="menu">
<a href="#" class="menu-element">001</a>
<a href="#" class="menu-element">002</a>
</div>
来源:http://www.paulund.co.uk/use-jquery-to-highlight-active-menu-item
答案 2 :(得分:0)
<style>
.myactive{
background-color:#F7A751;
}
</style>
<script type="text/javascript">
$(function () {
var url = window.location.pathname;
var activePage = url.substring(url.lastIndexOf('/') + 1);
activePage === '' ? $('#home').addClass("myactive") : $('#home').removeClass("myactive") ; // for active index page
activePage === 'about-us' ? $('#about').addClass("myactive") : $('#about').removeClass("myactive") ; //active about us
activePage === 'who-we-are' ? $('#info').addClass("myactive") :
$('#info').removeClass("myactive") ;
});
</script>
#HTML Part....
<li id="home"><a href="#">Home</a></li>
<li id="about"><a href="#">About</a></li>