【问题标题】:changing button color with javascript用javascript改变按钮颜色
【发布时间】:2023-04-07 08:24:02
【问题描述】:

我希望我的按钮在点击时改变颜色 [假设为黑色],但在页面刷新时我不希望它把颜色改回原来的颜色。

<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>

【问题讨论】:

  • 用 JavaScript just 是不可能的。
  • 有什么理由不使用 jQuery 吗?使用 jQuery 真的很容易

标签: javascript html css onclick action


【解决方案1】:
<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

【讨论】:

    【解决方案2】:

    您可以使用本地存储在页面刷新后保留颜色。

    window.onload = function(){
    
        var btn = document.getElementById("btn");
    
        if(localStorage["bg-color"]){
            btn.style.backgroundColor = localStorage.getItem("bg-color");
        };
    
        btn.onclick = function(){
            if(!localStorage["bg-color"]){
                localStorage.setItem("bg-color", "yellow");
            };
            btn.style.backgroundColor = localStorage.getItem("bg-color");
        };
        // remove from storage localStorage.removeItem("bg-color")
    };
    

    【讨论】:

      【解决方案3】:

      当你使用 JavaScript 获取一个元素时,你可以访问这个元素的一堆属性。
      两种解决方案可以修改他的属性:

      • 修改css属性(myElement.style.myProperty = 'myNewValue')
      • 修改班级列表(myElement.classList.add('myClassName'))

      作者编辑后更新:

      您可以在按钮上调用函数onclick="..."
      该函数会为这个按钮添加一个类来改变他的风格。
      然后将按钮的状态存储在您的 localStorage、会话、cookie 或数据库中,并带有布尔值(例如 clicked = true)。
      下次访问该页面时,如果单击 == true,则添加检查 onload 以在此按钮上添加此类。

      【讨论】:

        【解决方案4】:

        您可以使用 cookie 来存储页面重新加载之间的颜色状态,这是一个基本示例。

        function setColor(color){
          document.querySelector('#button').style.background = color
          document.cookie = `color=${color};`
        }
        
        function getColor() {
          return document.cookie.split('; ')      // ['color=blue']
            .reduce((acc, x) => {
              const [ key, value ] = x.split('=') // ['color', 'blue']
              acc[key] = value                    // { color: 'blue' }
              return acc
            })
            .color
        }
        
        // run the functions on page load
        window.addEventLister('DOMContentLoaded', function(){
          setColor(getColor())
        })
        
        setColor('#bada55')
        .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;
        }
        <h2>CSS Buttons</h2>
        <input id="button" type="button" class="button" value="Input Button">

        【讨论】:

        • 如果用户删除了浏览器的cookies,所有的数据都会丢失。你能建议任何其他的方式来设置永久的属性,即使在刷新页面后。
        • 仅当您将其存储在某个数据库中时。
        猜你喜欢
        • 1970-01-01
        • 2015-11-23
        • 1970-01-01
        • 1970-01-01
        • 2013-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-25
        相关资源
        最近更新 更多