简体   繁体   English

单击时更改锚点的颜色?

[英]Change the color of Anchor when clicked?

Noob here. 菜鸟在这里。 I have these 3 buttons type anchors and I want to change their color when they are clicked. 我有这3个按钮类型的锚点,我想在单击它们时更改其颜色。 I'm almost there but the thing is when the color changes if you click elsewhere in the page the color goes back to original color. 我快到了,但问题是,如果您在页面的其他位置单击颜色,则颜色会恢复为原始颜色。

Here is my code. 这是我的代码。 and I believe to fulfill the requirements javascript will be needed so I'm giving it a javascript tag. 并且我相信要满足要求,就需要javascript,因此我给它添加了javascript标签。

 .button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .button:active { background: red; } .button:focus { background: red; } 
 <a href="#" class="button">Link 1</a> <a href="#" class="button">Link 2</a> <a href="#" class="button">Link 3</a> 

add this to ur css 将此添加到ur css

.button:visited{
    background: blue;
}

all links clicked will change color 单击的所有链接将更改颜色

More info here link 更多信息在这里链接

 .button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .button:active { background: red; } .button:focus { background: red; } .button:visited { background: blue; } 
 <a href="#/test3" class="button">Link 1</a> <a href="#/test2" class="button">Link 2</a> <a href="#/test" class="button">Link 3</a> 

Try this js code 试试这个js代码

 var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { links[i].onclick = function() { this.style.backgroundColor = "red"; } } 
 .button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .button:active { background: red; } .button:focus { background: red; } 
 <a href="#" class="button">Link 1</a> <a href="#" class="button">Link 2</a> <a href="#" class="button">Link 3</a> 

I think you are looking for this: https://www.w3schools.com/howto/howto_js_active_element.asp 我认为您正在寻找的是: https : //www.w3schools.com/howto/howto_js_active_element.asp

This will add active class to the button (you can simply change that to your a tags) you clicked on. 这将为您单击的按钮添加活动类(您可以将其简单地更改为您的标签)。 Even after you will click elsewhere on the screen. 即使您将单击屏幕上的其他位置。

Hope it solved it, and good luck! 希望它解决了,祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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