javascript 按下时输入类型按钮会改变颜色?

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

Input type button changes color while pressed?

javascripthtmlbuttonjavascript-eventsinput

提问by Gianclè Monna

I want my input type=button to change color only while pressed. For example, if I have a white button, I want it to become green only while pressed, and when it's no more pressed I wish it returns white. How can I do this in HTML and Javascript? (sorry for my bad English and thank you)

我希望我的 input type=button 仅在按下时更改颜色。例如,如果我有一个白色按钮,我希望它仅在按下时变为绿色,当不再按下时我希望它返回白色。我怎样才能在 HTML 和 Javascript 中做到这一点?(抱歉我的英语不好,谢谢)

回答by Moin Zaman

the CSS selector for this state is called :active

调用此状态的 CSS 选择器 :active

So if you do:

所以如果你这样做:

input.btn:active { background:green }

input.btn:active { background:green }

that should work.

那应该工作。

See demo

演示

回答by Yuriy Galanter

Plain vanilla HTML + JavaSctipt:

普通的 HTML + JavaSctipt:

<input type="button" style="background-color:white" value="Click Me" onmousedown="this.style.background='green'" onmouseup="this.style.background='white'" />

Demo: http://jsfiddle.net/bqjzq/

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

回答by isgoed

For me it only works with:

对我来说,它只适用于:

<style>
input:active{  background-color:green}
</style>

Another option is to specify on mouse over, for buttons only:

另一种选择是在鼠标悬停时指定,仅用于按钮:

<style>
input[type=button]:hover{  background-color: #46000D}
<style>