CSS:如何在<a> link?

时间:2016-07-15 08:38:11

标签: html css

I know that press signal in css is :active, but i still can't find a proper way to make a toggle switch for the link.

For example, <a> has the color blue, when <a> will be pressed first time, it's color should be red, when it is pressed second time, it's color should blue again. So basically first press is a toggle switch from blue to red, and second is vice versa.

I have used :target action which didn't seem to work out:

a {
    color: blue;
}
a:active {
    color: red;
}
a:target {
    color: red;
}

How could this be possible without use of JS? So i could toggle switch the link color to red on the first click, and then blue again at the second.

3 个答案:

答案 0 :(得分:2)

没有JS,这是不可能实现的。链接不是设计为切换元素,CSS没有跟踪元素的多次点击(它被点击或不被点击)。

如果要表示切换,请查看复选框输入。他们有:checked pseudo-class

答案 1 :(得分:2)

您可以通过复选框和标签来完成。

<强> HTML:

<input type="checkbox" id="t1" class="toggle">
<a href="#"><label for="t1">Link with toggling color</label></a>

<强> CSS:

.toggle {
  position: absolute;
  left: -99em;
}

.toggle:not(:checked) + a {
  color: blue;
}

.toggle:checked + a {
  color: red;
}

工作示例here

答案 2 :(得分:0)

有一种方法可以(有点)用CSS完全实现这一点,但这意味着,在初始状态下,链接实际上是不可点击的,这可能是不可取的。

诀窍是将锚标记的pointer-events设置为echo <<< 'END_OF_TEXT',将其包含在具有tabindex属性的另一个元素中(以使其获得焦点)然后,当包装元素接收焦点,更改锚点的颜色并重置其none。在下一次单击时,链接将获得焦点,但这将从包装元素中移除焦点,这将使锚点的样式恢复到其初始状态。

pointer-events
*{color:#000;font-family:sans-serif;outline:0;}
a{
    color:#00f;
    pointer-events:none;
}
span:focus>a{
    color:#f00;
    pointer-events:initial;
}

相关问题