[英]Change background-color of button with JavaScript
I'm writing a HTML webPage, I use a button and I need to change his background-color on mouseover using a javascript function. 我正在编写一个HTML网页,我使用了一个按钮,并且需要在鼠标悬停时使用javascript函数更改他的背景颜色。 Here is the code. 这是代码。
<button onmouseover="funzione(this)">BTN</button>
<script>
funzione(x){
x.style.background-color=#ffffff;
}
</script>
In JavaScript you need get handler to element x
eg: 在JavaScript中,您需要获取元素x
处理程序,例如:
var x = document.getElementById("x");
but you should do this with CCS: 但是您应该使用CCS进行此操作:
button{
background-color: yellow;
}
button:hover{
background-color: lime;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/:hover https://developer.mozilla.org/zh-CN/docs/Web/CSS/:hover
This is very basic. 这是非常基本的。 You're missing keyword function
, and with that style of accessing properties, you need to use camel case. 您缺少关键字function
,并且具有访问属性的样式,因此需要使用驼峰式大小写。 Finally, wrap the color hex within quotes. 最后,将颜色十六进制用引号引起来。
function funzione(x){ x.style.backgroundColor= '#ffffff'; }
<button onmouseover="funzione(this)">BTN</button>
The recommended way is use CSS in production, but if you're just into JavaScript and want to explore, it's fine. 推荐的方法是在生产环境中使用CSS,但是如果您只喜欢JavaScript并且想要探索,那就很好了。
If you want in js: 如果要使用js:
<button onmouseover="set_color(this)">BTN</button> <script> function set_color(x){ x.style.backgroundColor='red'; } </script>
function funzione(x){ x.style.backgroundColor = "#ffffff"; }
<button onmouseover = "funzione(this)">BTN</button>
You can do this simply in CSS, its easy, efficient and less code. 您可以在CSS中轻松,高效且更少的代码来完成此操作。
<style type="text/css">
.myHoverButton:hover { background-color: #ffffff; }
</style>
<button id="button1" class="myHoverButton">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.