如何根据 URL 路径添加 CSS 类
How to add a CSS class depending on URL path?
如何根据我所在的路径将 CSS 类添加到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 # -->
jsfiddle.net/zatox50/wBxkj/
示例索引.html
jQuery(function($){
switch(window.location.hash){
case "vs": $(".popup").addClass("class1"); break;
case "bod": $(".popup").addClass("class2"); break;
case "ptf": $(".popup").addClass("class3"); break;
}
});
这些都
不适合我。 这有效:
<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
这是使用 JavaScript 和 JQuery 为网站创建动态活动菜单的简单代码。
<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>
相关文章:
- 如何添加CSS&JavaScript进入Windows窗体应用程序C#.net
- 对于每个json结果,使用类jquery添加css
- 为未标记的文本添加CSS样式
- 在WordPress中使用JavaScript在html元素上添加css类
- jQuery检查CSS宽度是否大于0,然后添加CSS属性
- 单击禁用的按钮添加 CSS
- 在 Twig Child 中添加 CSS 和 JavaScript
- 更改现有的css属性,并通过删除或添加css元素来使用它
- Ember.js为特定的模型id添加css类
- 我可以用添加css吗!重要的是,只使用jquery
- Regex用于添加CSS类
- 如何在一个表的输入中搜索一组特定的值,而不是另一个表's id(s)值以添加css
- 使用JQuery添加css属性悬停
- 通过程序添加CSS渐变作为背景图像
- 使用JS添加CSS规则
- 如何为Fabric.js中的文本添加CSS属性
- IE7/8未添加css属性'top'动态地作为内联样式
- 通过jquery损坏的旋转木马添加css样式
- Node.js Express应用程序:如果存在cookie,则从服务器端向元素添加CSS类
- 添加css转换时间以使用javascript切换类