如何通过单击按钮将背景色保存在Cookie中? [英] How to save background color in cookie through button click?

查看:113
本文介绍了如何通过单击按钮将背景色保存在Cookie中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试学习JavaScript中的Cookie。

Im currently trying to learn about cookies in javascript.

我的问题是:我有三个按钮,红-绿-蓝,如果我点击红色,红色应该保存在cookie中,这样我才能重新加载网页红色。

My question is : I have three Button Red-Green-Blue and if i click for example on red, the background color red should be saved within a cookie so that i reload the webpage its colored red.

document.cookie ="red";
document.cookie ="green";
document.cookie ="blue";
function BackgroundRed(){
document.cookie = "background-color=red";
}


<button onClick="BackgroundRed()" style="background-color:red">Rot</button>
<button onClick="alertCookie()" style="background-color:green">Grün</button>
<button onClick="alertCookie()" style="background-color:blue">Blau</button>


推荐答案

您可以这样做:

window.addEventListener('DOMContentLoaded', function() {
  var cookieValue = getCookie('backgroundColor'),
      btns = document.querySelectorAll('.color-btn');

  if (cookieValue) {
    setBackgroundColor(cookieValue);
  }
  
  Array.from(btns).forEach(function(btn) {
    btn.addEventListener('click', function() {
      var color = this.getAttribute('data-color');
      setBackgroundColor(color);
    });
  });
});

function setBackgroundColor(color) {
  document.body.style.backgroundColor = color;
  setCookie('backgroundColor', color);
}

function getCookie(name) {
  var cookies = document.cookie.split(';'),
      cookie = cookies.find(function(str) { return str.indexOf(name + '=') === 0; });
  if (cookie) {
    return cookie.split('=')[1];
  }
  return null;
}

function setCookie(name, value) {
  document.cookie = name + '=' + value;
}

body { background: red; }
button { padding: 1em; }
[data-color="red"] { background: red; }
[data-color="blue"] { background: blue; }
[data-color="green"] { background: green; }

<button class="color-btn" data-color="red"></button>
<button class="color-btn" data-color="blue"></button>
<button class="color-btn" data-color="green"></button>


注意:此演示无法在Stack Overflow上运行,因为它已被沙盒化并且不接受cookie

Note: this demo won't work on Stack Overflow because it is sandboxed and does not accept cookies

编辑:

在上面的示例中,为清晰起见,我没有在Cookie上设置有效期限。这意味着该cookie仅在当前会话期间保留((即,当您关闭所有浏览器的标签时,它将消失))。您可以选择将其保留更长的时间。例如,一年:

In the example above, I did not set an expiry date on the cookie for clarity. This means that the cookie will only stay during the current session (i.e. when you close all of your browser's tabs, it will be gone). You can choose to keep it for a longer period. For example, a year:

var expiry = new Date();
expiry.setFullYear(expiry.getFullYear() + 1);
document.cookie = name + '=' + value + '; expires=' + expiry.toUTCString() + ';';

这篇关于如何通过单击按钮将背景色保存在Cookie中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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