gpt4 book ai didi

javascript - 我正在尝试使用 vanilla JS 突出显示单击的 anchor 并删除先前突出显示的 anchor

转载 作者:行者123 更新时间:2023-12-03 07:20:13 24 4
gpt4 key购买 nike

这是我的第一篇文章,我还不知道自己在做什么,所以请耐心等待。

我正在尝试使用 vanilla JS 突出显示单击的 anchor 并删除之前突出显示的 anchor 。

我不确定为什么它不起作用,但我对此很陌生。

My CodePen

下面只是JS。 .nav-link 是链接类。 active 是应该在单击后对其进行操作的类。

window.onload = afterClick;


function afterClick(){
//set an on off array to toggle.
let linkClass = document.querySelectorAll(".nav-link");

linkClass.forEach(link => link.addEventListener("click", function(){
if (link.classList.contains("active")) {
link.classList.remove("active");
link.classList.add("active");
}}));
}

谢谢!

最佳答案

您可以监听 hashchange 事件来代替 onload 来实现此目的,如下所示:

window.addEventListener("hashchange", () => {
let hash = window.location.hash;
if (hash) {
let linkClass = document.querySelectorAll(".nav-link");
linkClass.forEach(x => x.classList.remove("active"))
document.querySelector('a[href="' + hash + '"]').classList.add("active");
}
});

因此,每当 url 哈希发生更改时,它都会使用以下方法从所有链接中删除 active 类:

linkClass.forEach(x => x.classList.remove("active"))

然后它将搜索具有该哈希的链接,并仅使用以下方法将active类添加到该链接:

document.querySelector('a[href="' + hash + '"]').classList.add("active");

工作演示:

window.addEventListener("hashchange", () => {
let hash = window.location.hash;
if (hash) {
let linkClass = document.querySelectorAll(".nav-link");
linkClass.forEach(x => x.classList.remove("active"))
document.querySelector('a[href="' + hash + '"]').classList.add("active");
}
});
#main-doc{font-family:Montserrat,sans-serif}#navbar{float:left;position:fixed;font-family:Montserrat,sans-serif;font-weight:700;min-width:230px;max-width:231px;height:100vh;background:url(https://image.freepik.com/free-vector/elegant-white-texture-background_23-2148431731.jpg);margin-top:-10px;margin-left:-10px;margin-right:40px;margin-bottom:25px;border:1px solid #000}#navbar header{padding:14px;font-size:1.8em;text-align:center;border:1px solid #000}#navbar a{display:block;color:#000;text-decoration:none;padding:15px;font-size:1.1em;text-align:center;border:1px solid #000;border-top:0}.main-section header{margin-left:30px;font-family:Notable,sans-serif;font-size:1.4rem}.main-section ul li{list-style-type:none;font-size:1.3em;padding-bottom:6px}.main-section{margin-left:230px;margin-right:50px;padding-top:20px}#main-doc{padding-bottom:60px}code{font-size:1rem;font-family:Montserrat,sans-serif}.active{color:orange!important;background-color:#00f!important}@media only screen and (max-width:425px){#navbar{max-width:425px;min-width:200px;position:relative;width:100vw;height:auto}.nav-link{margin-top:0;width:100vw}.main-section{margin-left:5px;margin-right:10px;padding-top:20px}.main-section ul{padding-left:5px}.navbar a{padding:0}}
<style>
@import url('https://fonts.googleapis.com/css2?family=Montserrat&family=Notable&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@700&display=swap');
</style>
<!-- font-family: 'Montserrat', sans-serif;
font-family: 'Notable', sans-serif; -->

<nav id="navbar">
<header style="color: #FFDF01 ;background: url(https://img.freepik.com/free-photo/blue-with-vignette-marble-texture-background-with-copy-space_23-2148327728.jpg?size=626&ext=jpg)">Common Sharks</header>
<a class="nav-link" href="#About_Sharks" id="aboutSharks">About Sharks</a>
<a class="nav-link" href="#The_Great_White">The Great White</a>
<a class="nav-link" href="#Oceanic_White_Tip">Oceanic White Tip</a>
<a class="nav-link" href="#Bull_Shark">Bull Shark</a>
<a class="nav-link" href="#Tiger_Shark">Tiger Shark</a>
</nav>
<main id="main-doc">
<section class='main-section' id="About_Sharks">
<header>About Sharks</header>
</br>

<ul><span style="font-size: 2.1em; margin-left: 5px;">B</span>efore we can talk about the most deadly sharks in the world, there are a few interesting facts that will help you understand sharks as a species better.</br>
</br>
<li>Sharks do not have bones</li>
<p>Sharks use their gills to filter oxygen from the water. They are a special type of fish known <i>Elasmobranch</i>, which translates into: </br>fish made of cartilaginous tissues—the clear gristly stuff that your ears and nose tip are made of. This
category also includes rays, sawfish, and skates. Their cartilaginous skeletons are much lighter than true bone and their large livers are full of low-density oils, both helping them to be buoyant. </p>


<p>Even though sharks don't have bones, they still can fossilize. As most sharks age, they deposit calcium salts in their skeletal cartilage to strengthen it. The dried jaws of a shark appear and feel heavy and solid; much like bone. These same minerals
allow most shark skeletal systems to fossilize quite nicely. The teeth have enamel so they show up in the fossil record too.</p>
</br>
<li>Most sharks have good eyesight</li>
<p>Most sharks can see well in dark lighted areas, have fantastic night vision, and can see colors. The back of sharks’ eyeballs have a reflective layer of tissue called a tapetum. This helps sharks see extremely well with little light.</p>
<br><br>
<li>Sharks have special electroreceptor organs</li>
<p>Sharks have small black spots near the nose, eyes, and mouth. These spots are the <i>ampullae of Lorenzini</i> – special electroreceptor organs that allow the shark to sense electromagnetic fields and temperature shifts in the ocean.</p>
<br>
<li>Shark skin feels similar to sandpaper</li>
<p>Shark skin feels exactly like sandpaper because it is made up of tiny teeth-like structures called placoid scales, also known as dermal denticles. These scales point towards the tail and help reduce friction from surrounding water when the shark
swims.
</p>
<br>
<li>Sharks can go into a trance</li>
<p>When you flip a shark upside down they go into a trance like state called tonic immobility. This is the reason why you often see sawfish flipped over when our scientists are working on them in the water.</p>
</br>
<li>Sharks have been around a very long time</li>
<p>Based on fossil scales found in Australia and the United States, scientists hypothesize sharks first appeared in the ocean around 455 million years ago.</p>
<br>
<li>Scientists age sharks by counting the rings on their vertebrae</li>
<p><code>Vertebrae contain concentric pairs of opaque and translucent bands. Band pairs are counted like rings on a tree and then scientists assign an age to the shark based on the count. Thus, if the vertebrae has 10 band pairs, it is assumed to be 10 years old. Recent studies, however, have shown that this assumption is not always correct. Researchers must therefore study each species and size class to determine how often the band pairs are deposited because the deposition rate may change over time. Determining the actual rate that the bands are deposited is called <i>validation</i>.</code></p>
<br>
<li>Blue sharks are really blue</li>
<p><code>The blue shark displays a brilliant blue color on the upper portion of its body and is normally snowy white beneath. The mako and porbeagle sharks also exhibit a blue coloration, but it is not nearly as brilliant as that of a blue shark. In life, most sharks are brown, olive, or grayish.</code></p>
<br>
<li>Each whale shark’s spot pattern is unique as a fingerprint</li>
<p>Whale sharks are the biggest fish in the ocean. They can grow to 12.2 meters and weigh as much as 40 tons by some estimates! Basking sharks are the world's second largest fish, growing as long as 32 feet and weighing more than five tons.</p>
<br>
<li>Some species of sharks have a spiracle that allows them to pull water into their respiratory system while at rest</li>
<p>Most sharks have to keep swimming to pump water over their gills A shark's spiracle is located just behind the eyes which supplies oxygen directly to the shark's eyes and brain. Bottom dwelling sharks, like angel sharks and nurse sharks, use this
extra respiratory organ to breathe while at rest on the seafloor. It is also used for respiration when the shark's mouth is used for eating.</p>
<br>
<li>Not all sharks have the same teeth</li>
<p>
Mako sharks have very pointed teeth, while white sharks have triangular, serrated teeth. Each leave a unique, tell-tale mark on their prey. A sandbar shark will have around 35,000 teeth over the course of its lifetime! </p>
<br>
<li>Different shark species reproduce in different ways</li>
<p>
Sharks exhibit a great diversity in their reproductive modes. There are oviparous (egg-laying) species and <i>viviparous</i> (live-bearing) species. Oviparous species lay eggs that develop and hatch outside the mother's body with no parental care
after the eggs are laid.</p>

</section>
<section class='main-section' id="The_Great_White">
<header>The Great White</header>
<ul>
The legendary great white shark is far more fearsome in our imaginations than in reality. As scientific research on these elusive predators increases, their image as mindless killing machines is beginning to fade.

</br>
</br>
<li>Shark Attacks</li>

Of the <i><b>100-plus</b></i> annual shark attacks worldwide, fully one-third to one-half are attributable to great whites. However, most of these are not fatal, and new research finds that great whites, who are naturally curious, are "sample biting"
then releasing their victims rather than preying on humans. It's not a terribly comforting distinction, but it does indicate that humans are not actually on the great white's menu.

</br>
</br>
<li>Characteristics</li>

Great whites are the largest predatory fish on Earth. They grow to an average of 15 feet in length, though specimens exceeding 20 feet and weighing up to 5,000 pounds have been recorded. They have slate-gray upper bodies to blend in with the rocky coastal
sea floor, but get their name from their universally white underbellies. They are streamlined, torpedo-shaped swimmers with powerful tails that can propel them through the water at speeds of up to 15 miles per hour. They can even leave the water
completely, breaching like whales when attacking prey from underneath.

</br>
</br>
<li>Hunting Adaptations</li>

Highly adapted predators, their mouths are lined with up to 300 serrated, triangular teeth arranged in several rows, and they have an exceptional sense of smell to detect prey. They even have organs that can sense the tiny electromagnetic fields generated
by animals. Their main prey items include sea lions, seals, small toothed whales, and even sea turtles, and carrion.

</br>
</br>
<li>Population</li>


</code>Found in cool, coastal waters throughout the world, there is no reliable data on the great white's population. However, scientists agree that their number are decreasing precipitously due to overfishing and accidental catching in gill nets, among
other factors, and they are considered a vulnerable species.</code>
</ul>
</section>
<section class='main-section' id="Oceanic_White_Tip">
<header>Oceanic White Tip</header>
<ul>
</br>
<li>Characteristics</li>
This is an active, almost fearless shark also associated with human attacks. MarineBio considers this shark the most potentially dangerous after great whites, tiger, and bull sharks, especially for open-ocean divers. This species is likely responsible
for open-ocean attacks following air or sea disasters.
</br>
</br>
<li>Behavior</li>
Oceanic whitetips can be very aggressive and unpredictable in the presence of potential prey. Sold commercially fresh, frozen, smoked, and dried-salted for human consumption; hides for leather, fins for shark fin soup, liver oil for vitamins, and processed
into fishmeal.
</br>
This species is a widespread and common large pelagic shark of warm oceanic waters. It presumably has a low reproductive capacity, but is extremely abundant and wide-ranging and is subject to fishery pressure as a common bycatch species with tuna and
other pelagic species. This bycatch is reportedly either inadequately reported or unrecorded. The fins are highly prized in trade although the carcass is often discarded. Fishery pressure is likely to persist, if not increase in future, and the
impact of this fishing pressure is presently unknown.
</br>
</br>
<li>Population</li>

<code>The oceanic whitetip shark, <i>Carcharhinus longimanus</i>, is listed as Critically Endangered.</code>
</ul>
</section>
<section class='main-section' id="Bull_Shark">
<header>Bull Shark</header>
<ul>
Bull sharks are aggressive, common, and usually live near high-population areas like tropical shorelines. They are not bothered by brackish and freshwater, and even venture far inland via rivers and tributaries.

</br>
</br>
<li>Human Encounters</li>

Because of these characteristics, many experts consider bull sharks to be the most dangerous sharks in the world. Historically, they are joined by their more famous cousins, great whites and tiger sharks, as the three species most likely to attack humans.

</br>
</br>
<li>Characteristics</li>

Bull sharks get their name from their short, blunt snout, as well as their pugnacious disposition and a tendency to head-butt their prey before attacking. They are medium-size sharks, with thick, stout bodies and long pectoral fins. They are gray on top
and white below, and the fins have dark tips, particularly on young bull sharks.

</br>
</br>
<li>Hunting</li>

They are found cruising the shallow, warm waters of all the world’s oceans. Fast, agile predators, they will eat almost anything they see, including fish, dolphins, and even other sharks. Humans are not, per se, on their menus. However, they frequent
the turbid waters of estuaries and bays, and often attack people inadvertently or out of curiosity.

</br>
</br>
<li>Threats to Survival</li>

<code>Bull sharks are fished widely for their meat, hides, and oils, and their numbers are likely shrinking. One study has found that their average lengths have declined significantly over the past few decades.</code>
</ul>
</section>
<section class='main-section' id="Tiger_Shark">
<header>Tiger Shark</header>
<ul>
Tiger sharks are named for the dark, vertical stripes found mainly on juveniles. As these sharks mature, the lines begin to fade and almost disappear.

</br>
</br>
<li>Shark Attacks</li>

These large, blunt-nosed predators have a duly earned reputation as man-eaters. They are second only to great whites in attacking people. But because they have a near completely undiscerning palate, they are not likely to swim away after biting a human,
as great whites frequently do.

</br>
</br>
<li>Hunting</li>

They are consummate scavengers, with excellent senses of sight and smell and a nearly limitless menu of diet items. They have sharp, highly serrated teeth and powerful jaws that allow them to crack the shells of sea turtles and clams. The stomach contents
of captured tiger sharks have included stingrays, sea snakes, seals, birds, squids, and even license plates and old tires.

</br>
</br>
<li>Population</li>

Tiger sharks are common in tropical and sub-tropical waters throughout the world. Large specimens can grow to as much as 20 to 25 feet in length and weigh more than 1,900 pounds.

</br>
</br>
<li>Threats to Survival</li>

<code>They are heavily harvested for their fins, skin, and flesh, and their livers contain high levels of vitamin A, which is processed into vitamin oil. They have extremely low repopulation rates, and therefore may be highly susceptible to fishing pressure. They are listed as near threatened throughout their range.</code>
</ul>
</section>
</main>

关于javascript - 我正在尝试使用 vanilla JS 突出显示单击的 anchor 并删除先前突出显示的 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62681980/

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