Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

javascript - How to save background color in cookie through button click?

Im currently trying to learn about cookies in javascript.

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it like this:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...