我目前正在尝试创建一个导航栏,当悬停在链接上时该导航栏会填充。但是,我还希望在相关页面上填充(或突出显示)链接。任何帮助将不胜感激!
注意:此代码是从开源中检索到的。我是网络技术的新手,正在为一个网络元素工作。
/*NAVIGATION */
body {
font-family: 'Roboto', sans-serif;
padding: 0;
margin: 0;
}
small {
font-size: 12px;
color: rgba(0, 0, 0, 0.4);
}
h1 {
text-align: center;
padding: 50px 0;
font-weight: 800;
margin: 0;
letter-spacing: -1px;
color: inherit;
font-size: 40px;
}
h2 {
text-align: center;
font-size: 30px;
margin: 0;
font-weight: 300;
color: inherit;
padding: 50px;
}
.center {
text-align: center;
}
section {
height: 100vh;
}
nav {
width: 60%;
margin: 0 auto;
background: #fff;
padding: 10px 0;
box-shadow: 0px 5px 0px #dedede;
}
nav ul {
list-style: none;
text-align: center;
}
nav ul li {
display: inline-block;
}
nav ul li a {
display: block;
padding: 15px;
text-decoration: none;
color: #aaa;
font-weight: 800;
text-transform: uppercase;
margin: 0 10px;
}
nav ul li a,
nav ul li a:after,
nav ul li a:before {
transition: all .5s;
}
nav ul li a:hover {
color: #555;
}
/* stroke */
nav.stroke ul li a,
nav.fill ul li a {
position: relative;
}
nav.stroke ul li a:after,
nav.fill ul li a:after {
position: absolute;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 0%;
content: '.';
color: transparent;
background: #aaa;
height: 1px;
}
nav.stroke ul li a:hover:after {
width: 100%;
}
nav.fill ul li a {
transition: all 2s;
}
nav.fill ul li a:after {
text-align: left;
content: '.';
margin: 0;
opacity: 0;
}
nav.fill ul li a:hover {
color: #fff;
z-index: 1;
}
nav.fill ul li a:hover:after {
z-index: -10;
animation: fill 1s forwards;
-webkit-animation: fill 1s forwards;
-moz-animation: fill 1s forwards;
opacity: 1;
}
/* Keyframes */
@-webkit-keyframes fill {
0% {
width: 0%;
height: 1px;
}
50% {
width: 100%;
height: 1px;
}
100% {
width: 100%;
height: 100%;
background: #333;
}
}
<section style="background: #2ecc71; color: rgba(0, 0, 0, 0.5);">
<h2>Nav bar test</h2>
<nav class="fill">
<ul>
<li><a href="index.html">Home</a>
</li>
<li><a href="#">About</a>
</li>
<li><a href="#">Downloads</a>
</li>
<li><a href="#">More</a>
</li>
<li><a href="#">Contact</a>
</li>
</ul>
</nav>
</section>
最佳答案
最好的做法是为当前页面按钮添加一个“事件”类。
<li><a href="index.html" class="active">Home</a></li>
然后将“a.active”添加到您已有的每个“a:hover”,使其具有相同的 css。
nav.fill ul li a:hover,
nav.fill ul li a.active { /* Here */
color: #fff;
z-index: 1;
}
nav.fill ul li a:hover:after,
nav.fill ul li a.active:after { /* Here */
z-index: -10;
animation: fill 1s forwards;
-webkit-animation: fill 1s forwards;
-moz-animation: fill 1s forwards;
opacity: 1;
}
nav.stroke ul li a:hover:after,
nav.stroke ul li a.active:after { /* Here */
width: 100%;
}
这是一个 jsfiddle 实例:https://jsfiddle.net/884o5sjs/ (为了更快地获得帮助,记得下次创建自己的 jsfiddle)
您可以使用 php(建议)或什至使用 jQuery(不建议)将 class="active"动态添加到当前页面,但由于看起来您使用的是“.html”,因此您必须手动添加它在每一页上。
希望这对您有所帮助。
关于html - 在当前页面上填充导航栏链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39673148/