简体   繁体   English

仅当单击CSS时,如何才能更改按钮的颜色?

[英]How can I change the color of a button with CSS only when it is clicked?

I know there is an Active state but this appears and stays after I click on the button. 我知道有一个活动状态,但是在我单击按钮后,它会出现并保持不变。 Is there a way I can change the color of the button with CSS to show when the mouse is over the button and clicked only. 有没有一种方法可以用CSS更改按钮的颜色,以在鼠标悬停在按钮上方并单击时显示该颜色。

What I was thinking is something like a CSS selector for Focus and Active at the same time. 我当时想的是同时针对Focus和Active的CSS选择器。 Is there such a thing or way I could do this. 有没有可以做的事情或方式。 This would be something like I see with the button on Stackoverflow but with a change in color when clicked that goes away when I move the cursor away. 这就像我在Stackoverflow上的按钮上看到的一样,但是单击时颜色发生变化,而当我将光标移开时,颜色会消失。

What I get from your question is that you want a button to change its colour once it has been clicked? 我从您的问题中得到的是,您是否希望按钮一旦被单击就可以更改其颜色? If so you can try using JQuery which adds a css() function that allows you to change properties of elements. 如果是这样,您可以尝试使用添加了css()函数的JQuery,该函数允许您更改元素的属性。 So, to change the background colour of a button once it has been clicked you could adapt the following code: 因此,要更改单击按钮后的背景颜色,可以改写以下代码:

 $("button").click(function(){ $(this).css("background-color", "red"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Or else just use plain CSS: 否则,只需使用普通的CSS:

button:hover:focus

Hopefully this helps! 希望这会有所帮助!

Please check below examples and see if this is what you want. 请检查以下示例,看看这是否是您想要的。

JSFiddle1 JSFiddle1

 input { background: #2e9ec7; } input:active { background: #2fa832; } 
 <input type="submit"></input> 

JSFiddle2 JSFiddle2

 input { background: #2e9ec7; } input:hover, input:active { background: #2fa832; } 
 <input type="submit"></input> 

Hope this helps. 希望这可以帮助。

Use mouseup and mousedown events if you can use jquery. 如果可以使用jquery,请使用mouseup和mousedown事件。 On mousedown event set color of the button and on mouseup event set the color back to what is was before clicking it. 在mousedown事件中,设置按钮的颜色,在mouseup事件中,将颜色设置为单击之前的颜色。

<input type="submit">
input {
    background: blue;
}
input:active {
    background: red;
}

When it's active, the color would be red. 启用后,颜色将为红色。 Except for that moment, it will be blue. 除非那一刻,它会是蓝色的。 Also, you could change only the text color by setting the color property instead of the background one. 另外,您可以通过设置color属性而不是background颜色来仅更改文本颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM