Ich bin irgendwie verwirrt, warum mein Code nicht richtig funktioniert. Ich hoffe, Sie sagen mir, was ich falsch gemacht habe ... Ich möchte die Navigationsregisterkarte hervorheben, während Sie darauf klicken.
HTML:
<header class="mainheader">
<!-- Obrazek tutaj-->
<nav>
<ul>
<li><a id="a-home" onclick="dodajAktywne(this)" href="index.html">Home</a></li>
<li><a id="a-omnie" onclick="dodajAktywne(this)" href="omnie.html">O mnie</a></li>
<li><a id="a-kurs" onclick="dodajAktywne(this)" href="kurs.html">Kurs</a></li>
<li><a id="a-kontakt" onclick="dodajAktywne(this)" href="kontakt.html">Kontakt</a></li>
</ul>
</nav>
</header>
JavaScript:
function dodajAktywne(elem) {
var a = document.getElementsByTagName('a')
for (i = 0; i < a.length; i++) {
a[i].classList.remove('active');
}
elem.classList.add('active');
}
CSS:
.active {
color: blue;
background-color: #cf5c3f;
}
Sie können Ihr JavaScript für Folgendes vereinfachen:
function dodajAktywne(elem) {
// get all 'a' elements
var a = document.getElementsByTagName('a');
// loop through all 'a' elements
for (i = 0; i < a.length; i++) {
// Remove the class 'active' if it exists
a[i].classList.remove('active')
}
// add 'active' classs to the element that was clicked
elem.classList.add('active');
}
Wenn Sie den Parameter this
in Ihrem HTML-Code an Folgendes übergeben:
<header class="mainheader">
<!-- Obrazek tutaj-->
<nav>
<ul>
<li><a id="a-home" onclick="dodajAktywne(this)" href="#">Home</a>
</li>
<li><a id="a-omnie" onclick="dodajAktywne(this)" href="#">O mnie</a>
</li>
<li><a id="a-kurs" onclick="dodajAktywne(this)" href="#">Kurs</a>
</li>
<li><a id="a-kontakt" onclick="dodajAktywne(this)" href="#">Kontakt</a>
</li>
</ul>
</nav>
</header>
Hinweis: Ich habe das href
-Attribut in #
geändert. Sie müssen es wieder in Ihre .html
-Seiten ändern.
Alternativ können Sie dies auch ohne JavaScript tun, indem Sie die CSS-Codes :focus
verwenden:
a:focus {
color: blue;
background-color: #cf5c3f;
}
Dieser Code hebt die Navigationsregisterkarte hervor, ohne dass ein Klick in den HTML-Code eingefügt werden muss. Die Hintergrundfarbe wird jedoch nicht entfernt, wenn auf eine andere Registerkarte geklickt wird.
document.onclick = function(event) {
var target = event.target || event.srcElement;
target.style.background = '#cf5c3f';
};
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);