如何在刷新页面后避免更改按钮的颜色

时间:2016-07-16 20:52:10

标签: javascript html

您好我写了一个javascript代码来更改点击按钮的颜色,它工作正常(它的第一个颜色是白色,当我点击它变成绿色)现在我有一个问题
当我点击按钮,颜色变为绿色,如果之后我再次打开同一页面或重新加载颜色再次变成白色,我不想要那样。任何想法谢谢



<!DOCTYPE html>
<html>
<head>

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

<body>

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

</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

尝试使用localStorage。像这样:

      var startColor="#FFFFFF";//default color on first visit
      if (localStorage.startColor)startColor=localStorage.startColor;  //if page has been visited before then this color

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

答案 1 :(得分:0)

页面更改/重新加载/...

后,所有javascript对象都会刷新

您可能希望查看Cookie(在浏览器中存储数据并将其读回)。