javascript - 使用javascript更改按钮颜色

标签 javascript html css onclick action

i want my button to change color on click [suppose black],but on page refresh i dont want it to change its color back to original color.

<html>
    <head>
    <style>
    .button {
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
    }
    </style>
    </head>
    <body>

    <h2>CSS Buttons</h2>



    <input type="button" class="button" value="Input Button">

    </body>
    </html>

最佳答案

<html>
<head>
<script>
/* On load of the page we are calling this function which will
 give us the color name stored in our local storage */
        function changeColor() {
            var color = localStorage.getItem("colorName");
            document.getElementById("color").style.backgroundColor = color;
        }
/*This function will change the color of button on click*/
        var i = -1;
        function colorArray() {
            var arr = new Array();
            arr[0] = "Red";
            arr[1] = "Orange";
            arr[2] = "Green";
            arr[3] = "Blue";
            i++;
            if (i > arr.length - 1) {
                i = 0;
            }
/* We have an array with the color names, you can add any 
number of colors in this array */
/* After fetching the color from array we are storing 
it in the local storage of our browser for future use*/
            localStorage.setItem("colorName", arr[i]);
            document.getElementById("color").style.backgroundColor = arr[i];
        }
    </script>
</head>

<body onload="changeColor()">
    <button onclick="colorArray()" id="color"> Change Color </button>
</body>

</html>

Click here for Live Demo and complete source code

关于javascript - 使用javascript更改按钮颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068802/

相关文章:

css - 快速媒体查询故障

javascript - 获取提交类型以发布其值

用于验证整数值的 JavaScript 函数

javascript - 当父容器 angularJS 中有样式时,值不会更新

javascript - 使用没有类或 ID 的 HTML 页面元素

html - 更改 actionButton 及其标签的大小

javascript - 将变量设置为以 Null 返回的字符串

html - 为什么我的网站右边有空白?

html - 列表显示为 block 而不是内联 block

css - 更改背景定位区域