Html 仅使用 css 在单击时更改 div 背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27069142/
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-29 03:06:05  来源:igfitidea点击:

Change div background color on click using only css

csshtml

提问by Philip Loyer

So I have a div I want to change the color of when clicked. I have three divs over all and I want to denote which one is the active div when clicking on it

所以我有一个 div 我想改变点击时的颜色。我总共有三个 div,我想在点击它时指出哪一个是活动 div

Basically I want to use the CSS active property but not have the particular div change back when the mouse up occurs. Sort of like a focus. I am also using bootstrap if that is helpful

基本上我想使用 CSS active 属性,但在鼠标抬起时不让特定的 div 变回。有点像一个焦点。如果有帮助,我也在使用引导程序

Here is a example of the html

这是一个 html 的例子

<div>
    Section 1
</div>
<div>
    Section 2
</div>
<div>
    Section 3
</div>

Could anyone tell me how i could accomplish this without using javascript?

谁能告诉我如何在不使用 javascript 的情况下完成此任务?

回答by Yuriy Galanter

Make your DIVs focusable, by adding tabIndex:

通过添加 tabIndex 使您的 DIV 成为焦点:

<div tabindex="1">
Section 1
</div>

<div tabindex="2">
Section 2
</div>

<div tabindex="3">
Section 3
</div>

Then you can simple use :focuspseudo-class

然后你可以简单地使用:focus伪类

div:focus {
    background-color:red;
}

Demo: http://jsfiddle.net/mwbbcyja/

演示:http: //jsfiddle.net/mwbbcyja/

回答by Dhruv Naik

Try this, it worked for me:

试试这个,它对我有用:

div:active{  

    background-color:white;

}

回答by mario

div:focus {
    background-color:'color';
}