单击时更改Anchor的颜色?

时间:2018-05-05 18:46:12

标签: javascript css

Noob在这里。我有这3个按钮类型的锚点,我想在点击它们时更改它们的颜色。我几乎就在那里,但事情是,当你点击页面中的其他地方颜色发生变化时,颜色会恢复原来的颜色。

这是我的代码。而且我相信要满足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>

3 个答案:

答案 0 :(得分:2)

将此添加到ur css

.button:visited{
    background: blue;
}

点击的所有链接都会改变颜色

此处有更多信息link

&#13;
&#13;
.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;
}
&#13;
<a href="#/test3" class="button">Link 1</a>
<a href="#/test2" class="button">Link 2</a>
<a href="#/test" class="button">Link 3</a>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个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>

答案 2 :(得分:0)

我认为你正在寻找这个: https://www.w3schools.com/howto/howto_js_active_element.asp

这会将活动类添加到您单击的按钮(您只需将其更改为您的标记)。即使你点击了屏幕上的其他地方。

希望它解决了,祝你好运!

相关问题