更改按钮颜色 onClick [英] Change Button color onClick

查看:26
本文介绍了更改按钮颜色 onClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 Button 每次点击它时都会改变颜色.但它只会在第一次点击时改变颜色.

I want my Button to change color every time I click on it. But it only changes color on the first click.

我相信问题出在 setColor 函数中.每次单击 Button 时,count 都会设置为 1.因此,即使我将其设置为 0,下次单击时它也会重置为 1.我该如何解决?javascript/html 中是否有全局变量可以轻松解决?

I believe the problem is in the setColor function. Every time I click on the Button, count gets set to 1. So even when I set it to 0, it gets reset to 1 on the next click. How do I fix this? Are there global variables in javascript/html where this would easily be solved?

<!DOCTYPE html>
<html>
<head>

<script>
function setColor(btn, color){
    var count=1;
    var property = document.getElementById(btn);
    if (count == 0){
        property.style.backgroundColor = "#FFFFFF"
        count=1;        
    }
    else{
        property.style.backgroundColor = "#7FFF00"
        count=0;
    }

}
</script>
</head>

<body>

<input type="button" id="button" value = "button" style= "color:white" onclick="setColor('button', '#101010')";/>

</body>
</html>

推荐答案

javascript 中确实有全局变量.您可以详细了解范围,这在这方面很有帮助情况.

There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.

您的代码可能如下所示:

Your code could look like this:

<script>
    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "#7FFF00"
            count = 0;
        }
    }
</script>

希望这会有所帮助.

这篇关于更改按钮颜色 onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆