CSS css在单击时更改元素的样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6096046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:36:44  来源:igfitidea点击:

css change style of an element on click

cssonclickhrefvisited

提问by dana

I have a list of elements, and i want to change a style of an element when one clicks on the list element(and that specific style to stay the same until the user presses another list item).

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

I tried using the 'active' style, but no success.

我尝试使用“主动”样式,但没有成功。

My code:

我的代码:

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


#product_types a:active
{
    background-color:yellow;
}

but the element is 'yellow' only a millisecond, while i actually click on it...

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

回答by Sparky

Use the :focus pseudo class

使用 :focus 伪类

#product_types a:focus
{
 background-color:yellow;
}

See this example -> http://jsfiddle.net/7RASJ/

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

The focus pseudo class works on elements like form fields, links etc.

focus 伪类适用于表单字段、链接等元素。

回答by Biped

The reason it doesn't work in other browsers is related to the css focus specification. It states:

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

The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).

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

So it seems to work perfectly fine with text input fields or when you focus using the tab key. To make the above compatible with other browsers add the tabindex attribute to each element and this appears to fix the problem.

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

HTML:

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>

CSS:

CSS:

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

#product_types a:focus {     
    background-color:yellow;   
}

JSFiddle Example

JSFiddle 示例