![](/img/trans.png)
[英]How to change link Navbar color while scrolling in React or Gatsby?
[英]Change link color on scrolling
我有這個菜單:
<div id = "menu" >
<a href = "index.html"> <img src = "images/logo.png" style = "padding-left: 5%; padding-top: 1%;"> </a>
<ul id = "lista">
<li style = "display: inline-block;"> <a href = "aboutus.html"> <padding left> SOBRE O INSTITUTO </a></li>
<li style = "display: inline-block;"> <a href = "pessoas.html"> PESSOAS</a> </li>
<li style = "display: inline-block;"> <a href = "universidadefour.html"> UNIVERSIDADE FOUR </a>
<ul>
<a href = "programaprolider.html"> <li> PROGRAMA PROLÍDER </li> </a>
<a href = "universidadefour.html#escolapolitica"> <li> ESCOLA DE POLÍTICA </li> </a>
<a href = "universidadefour.html#escolaempreendedorismo"> <li> ESCOLA DE EMPREENDEDORISMO </li> </a>
</ul> </li>
<li style = "display: inline-block;"> <a href = "comunidadefour.html"> <padding left> COMUNIDADE FOUR </a>
<ul>
<a href = "comunidadefour.html"> <li> A COMUNIDADE FOUR</li> </a>
<a href = "comunidade.html"> <li> FELLOWS </li> </a>
</ul>
</li>
<li style = "display: inline-block;"> <a href = "foursummit.html"> FOUR SUMMIT </a> </li>
<li style = "display: inline-block;"> <a href = "trabalheconosco.html"> VAGAS ABERTAS</a> </li>
<li style = "display: inline-block;"> <a href = "en-index.html"> EN </a> <span style = "color: white;"> |</span> <a href = "index.html"> BR </a> </li>
</ul>
</div>
這些是鏈接顏色的 CSS 規范:
#menu ul li a{
text-decoration: none;
line-height: 70px;
font-size: 14px;
padding: 4px 15px 4px 15px;
color: white;
}
此菜單沒有任何指定的背景顏色。 但是,在用戶滾動頁面后,它會發生變化:
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
document.getElementById("menu").style.backgroundColor = "#fff";
} else {
document.getElementById("menu").style.backgroundColor = "";
}
}
我想用這個菜單的鏈接 colors 做同樣的事情。 我該怎么做,將鏈接 colors 從白色更改為 #333333?
謝謝!
使用document.querySelectorAll()
到 select 具有指定選擇器的元素。 學到更多
在您的 function 中,在if(){}
塊內,
var links = document.querySelectorAll("#lista a"); // selects all <a> inside #lista
links.forEach((link)=>link.style.color = "#333333"); // loop through each link and change the color
您可以使用 getElementsByTagName() 到具有指定標簽的 select 元素,然后逐個更改鏈接的顏色。
if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
var y = document.getElementsByTagName("a"); //Select all <a> tags
for (i = 0; i < y.length; i++) {
y[i].style.color = "#333333"; //Loop through links array and change the link color
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.