用JS保持动画链接样式



我使用了下面的例子来获得一个动画链接下划线效果悬浮:https://tobiasahlin.com/blog/css-trick-animating-link-underlines/

这是工作良好,但是,我想有下划线保留,而该页面的部分是在视图中。我使用下面的JS代码来添加或删除'current'类到适当的导航元素,这对于简单的事情很好,比如改变background-color:

window.onscroll = function() {
var navlinks = document.getElementsByTagName('nav')[0].getElementsByTagName('a');
var sections = document.getElementsByTagName('main')[0].getElementsByTagName('section');
for (var s = 0; s < sections.length; s++) {
var sectTop = sections[s].offsetTop - 1;
var sectBot = sections[s].offsetTop+sections[s].offsetHeight - 1;
if (window.scrollY >= sectTop && window.scrollY < sectBot) {
navlinks[s].classList.add('current');
} else {
navlinks[s].classList.remove('current');
}
}
}

我不确定如何保持下面CSS产生的下划线:

nav div a::before {
content: "";
position: absolute;
display: block;
width: 100%;
height: 2px;
bottom: 2vh;
left: 0;
background-color: #02081a;
transform: scaleX(0);
transition: transform 0.3s ease;
}
nav div a:hover::before {
transform: scaleX(1);
}

我已经尝试了一些东西,但它只是把它弄得一团糟。当适当的部分被瞄准时,如何让下划线保留,有什么想法吗?

全部排序,从

nav div a:hover::beforenav div a:hover::before, nav div a.current::before

@CBroe建议,谢谢大家

基本上,您所需要做的就是在CSS规则中添加您在滚动页面时分配的类名,以显示行。

window.onscroll = function() {
var navlinks = document.getElementsByTagName('nav')[0].getElementsByTagName('a');
var sections = document.getElementsByTagName('main')[0].getElementsByTagName('section');
for (var s = 0; s < sections.length; s++) {
var sectTop = sections[s].offsetTop - 1;
var sectBot = sections[s].offsetTop+sections[s].offsetHeight - 1;
if (window.scrollY >= sectTop && window.scrollY < sectBot) {
navlinks[s].classList.add('current');
} else {
navlinks[s].classList.remove('current');
}
}
}
window.onscroll();
nav div a {
position: relative;
text-decoration: none;
font-size: 24px;
display: inline-block;
}
nav div a.current::before,
nav div a:hover::before,
nav div a::before
{
transform: scaleX(1);
}
nav div a::before {
content: "";
position: absolute;
display: block;
width: 100%;
height: 2px;
bottom: 0;
left: 0;
background-color: red;
transition: transform 0.3s ease;
transform: scaleX(0);
}
nav div a:hover:not(.current)::before
{
background-color: green;
}
main
{
position: relative;
top: 5vh;
overflow: auto;
}
nav
{
position: fixed;
top: 0;
z-index: 1;
background-color: white;
width: 100%;
}
section
{
height: 150vh;
border: 1px solid black;
}
<nav>
<div>
<a href="#section1">section 1</a>
<a href="#section2">section 2</a>
<a href="#section3">section 3</a>
</div>
</nav>
<main>
<section id="section1"><h1>my section 1</h1></section>
<section id="section2"><h1>my section 2</h1></section>
<section id="section3"><h1>my section 3</h1></section>
</main>

相关内容

  • 没有找到相关文章

最新更新