简体   繁体   中英

How can I make only the last clicked anchor element <a> have a different color?

I have a sidebar, and I want the text in my anchor elements (Link 1,2,3 in my HTML) to change colour when clicked. Also, I would like to have only one coloured anchor element at a time, so the previous one should always be returned to its normal colour. How can this be done?

Here is my HTML: https://pastebin.com/ew9qXAzH

These are my anchor elements:

 <div class="sidenav"> <button class="dropdown-btn">Dropdown1 <i class="fa fa-caret-down"></i> </button> <div class="dropdown-container"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> <button class="dropdown-btn">Dropdown2 <i class="fa fa-caret-down"></i> </button> <div class="dropdown-container"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div>

Apparently :focus holds the "last clicked" color only until you click on something else in the page.

 a:focus { color: green; }
 <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a>

I gave all the links a class called "myLink" and an onclick function "linkClicked()". This is what the JavaScript looks like:

function linkClicked() {
    var links = document.querySelectorAll(".myLink"); // select all the links
    links.forEach(link => link.style.color = "#818181"); // set color of all links to default (gray)
    event.target.style.color = "red"; // set color of the link clicked to red (or the color you want)
}

There are corresponding css selectors for that.

a:link and     a:visited.

First one acts when link is in normal state and the second one acts when you click on specific link so you can go like >

a:link {
  color: red;
}

a:visited {
  color: green;
}

You can also use a:active which is triggered immediately when you click on link but the color would go back to normal as soon as click event is over(in other words the effect lasts like 0.01 sec)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM