gpt4 book ai didi

javascript - HTML & CSS : triggering active class for a section in index. html

转载 作者:行者123 更新时间:2023-12-05 00:33:01 25 4
gpt4 key购买 nike

所以通常当我访问前“index.html”并在我的导航栏中给我的href链接“事件”类或任何类并为其着色时,它定义了我所在的页面
所以

<a href="index.html" class="active">
a.active {
background-color: #009879;
color: white;
}
会做的伎俩并突出显示我目前在导航栏中的页面
但我的 index.html 中有一个部分,我可以通过在导航栏中单击它来访问
<a href="index.html#about">
但是如果我为此部分触发了 class="active",那么索引和部分都将在我的导航栏中突出显示
我该如何做到这一点,以便当我在该部分时,我的 index.html 失去其 class=active 并且该部分获得该类?
可能如果这可以只使用 CSS 来完成!
TL;DR 我需要一种在 CSS/JS 中添加/删除我希望它位于的任何元素的类的方法。

最佳答案

你好 , 你在你的元素中想要的功能叫做scrollspy,它是用javascript实现的。您可以使用 Bootstrap 或在纯 javascript 中创建函数。但是为了不重新发明轮子,我向您展示了一个基于 vanilla javascript 脚本的示例:https://github.com/cferdinandi/gumshoe .

var spy = new Gumshoe('#my-awesome-nav a');

html {
overflow-y: auto;
scroll-behavior: smooth;
}

/* Sets body width */
.container {
max-width: 90em;
width: 88%;
margin-left: auto;
margin-right: auto;
}

/**
* Grid
*/
.grid {
display: grid;
grid-gap: 2em;
grid-template-columns: 30% 70%;
}

#my-awesome-nav {
position: fixed;
}

#my-awesome-nav li.active {
background-color: black;
}

#my-awesome-nav li.active a {
color: white;
}

/**
* Sections
*/
.section {
color: #ffffff;
height: 95vh;
margin: 0;
padding: 2em;
}

#eenie {
background-color: #0088cc;
}

#meenie {
background-color: rebeccapurple;
}

#miney {
background-color: #272727;
}

#mo {
background-color: #f42b37;
}
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/gumshoe/dist/gumshoe.polyfills.min.js"></script>

<div class="container">
<div class="grid">
<nav>
<ul id="my-awesome-nav">
<li><a href="#eenie">Eenie</a></li>
<li><a href="#meenie">Meenie</a></li>
<li><a href="#miney">Miney</a></li>
<li><a href="#mo">Mo</a></li>
</ul>
</nav>
<main>
<div class="section" id="eenie">
Eenie...
</div>

<div class="section" id="meenie">
Meenie...
</div>

<div class="section" id="miney">
Miney...
</div>

<div class="section" id="mo">
Mo...
</div>

<p><a data-scroll href="#top">Back to the top</a></p>
</main>
</div>
</div>

关于javascript - HTML & CSS : triggering active class for a section in index. html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70560680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com