css在点击时更改元素的样式

dan*_*ana 5 css onclick href visited

我有一个元素列表,我想在单击列表元素时更改元素的样式(并且该特定样式保持不变直到用户按下另一个列表项).

我尝试使用'主动'风格,但没有成功.

我的代码:

#product_types
{       
    background-color: #B0B0B0;
position: relative; /*overflow: hidden;*/
}


#product_types a:active
{
    background-color:yellow;
}
Run Code Online (Sandbox Code Playgroud)

但元素是'黄色'只有一毫秒,而我实际点击它...

Spa*_*rky 13

使用:focus伪类

#product_types a:focus
{
 background-color:yellow;
}
Run Code Online (Sandbox Code Playgroud)

看这个例子 - > http://jsfiddle.net/7RASJ/

焦点伪类适用于表单字段,链接等元素.


小智 5

它在其他浏览器中不起作用的原因与 css 焦点规范有关。它指出:

:focus 伪类在元素具有焦点时适用(接受键盘事件或其他形式的文本输入)。

因此,它在文本输入字段或使用 Tab 键聚焦时似乎工作得非常好。为了使上述与其他浏览器兼容,向每个元素添加 tabindex 属性,这似乎解决了问题。

HTML:

<ul>
    <li id = 'product_types'><a href='#' tabindex="1">First</a></li>
    <li id = 'product_types'><a href='#' tabindex="2">Second</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

CSS:

#product_types  {
    background-color: #B0B0B0;
    position: relative;
}

#product_types a:focus {     
    background-color:yellow;   
}
Run Code Online (Sandbox Code Playgroud)

JSFiddle 示例