Jos*_*ren 41 html javascript css
一个样式如何链接当前页面与其他页面不同?我想交换文字和背景的颜色.
HTML:
<ul id="navigation">
<li class="a"><a href="/">Home</a></li>
<li class="b"><a href="theatre.php">Theatre</a></li>
<li class="c"><a href="programming.php">Programming</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
CSS:
li a{
color:#A60500;
}
li a:hover{
color:#640200;
background-color:#000000;
}
Run Code Online (Sandbox Code Playgroud)
小智 69
使用jQuery,您可以使用该.each
函数使用以下代码迭代链接:
$(document).ready(function() {
$("[href]").each(function() {
if (this.href == window.location.href) {
$(this).addClass("active");
}
});
});
Run Code Online (Sandbox Code Playgroud)
根据您的页面结构和使用的链接,您可能需要缩小选择范围,例如:
$("nav [href]").each ...
Run Code Online (Sandbox Code Playgroud)
如果您使用的是URL参数,则可能需要删除以下内容:
if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...
Run Code Online (Sandbox Code Playgroud)
这样您就不必编辑每个页面.
N 1*_*1.1 47
a:active
:当您单击链接并按住它时(激活!).
a:visited
:当链接已被访问时.
如果您希望突出显示与当前页面对应的链接,则可以为链接定义一些特定样式 -
.currentLink {
color: #640200;
background-color: #000000;
}
Run Code Online (Sandbox Code Playgroud)
仅li
在服务器端或客户端(使用JavaScript)将此新类添加到相应的(链接).
可以实现这一点,而无需单独修改每个页面(将"当前"类添加到特定链接),但仍然没有JS或服务器端脚本.这使用:target伪选择器,它依赖于#someid
出现在地址栏中.
<!DOCTYPE>
<html>
<head>
<title>Some Title</title>
<style>
:target {
background-color: yellow;
}
</style>
</head>
<body>
<ul>
<li><a id="news" href="news.html#news">News</a></li>
<li><a id="games" href="games.html#games">Games</a></li>
<li><a id="science" href="science.html#science">Science</a></li>
</ul>
<h1>Stuff about science</h1>
<p>lorem ipsum blah blah</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
有几个限制:
只要这些页面的任何链接都包含id,并且导航栏位于顶部,就不会有问题.
其他页内链接(书签)也会导致颜色丢失.
获取文档中的所有链接并将它们的参考 URL 与文档的 URL 进行比较。如果匹配,则向该链接添加一个类。
JavaScript
<script>
currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
currentLinks.forE??ach(function(link) {
link.className += ' current-link')
});
</script>
Run Code Online (Sandbox Code Playgroud)
One Liner Version of Above
document.querySelectorAll('a[href="'+document.URL+'"]').forE??ach(function(elem){e??lem.className += ' current-link')});
Run Code Online (Sandbox Code Playgroud)
CSS
.current-link {
color:#baada7;
}
Run Code Online (Sandbox Code Playgroud)
其他注意事项
上面 Taraman 的 jQuery 答案只搜索[href]
哪些将返回link
标签,而不是a
依赖于href
属性的标签。搜索a[href='*https://urlofcurrentpage.com*']
仅捕获那些符合条件的链接,因此运行速度更快。
此外,如果您不需要依赖 jQuery 库,那么 vanilla JavaScript 解决方案绝对是您要走的路。
归档时间: |
|
查看次数: |
192815 次 |
最近记录: |