页面重新加载时JavaScript cookie出现问题

时间:2019-11-23 14:31:04

标签: javascript cookies

我想创建一个脚本,该脚本在每次重新加载页面时随机添加10个div(使用库偶然.js)。之前的10个div应该保持相同的位置,为此,我正在使用javascript cookie库js.cookie.js。我设法做到了,但是由于某种原因,在重新加载8页之后它不再起作用了……知道为什么吗?

var numberOfDiv = 10;
var currentLength = Cookies.get("pixelLength");
var states = ["stuck"];
var colors = ["rgb(255,0,0)", "rgb(0,255,0)", "rgb(0,0,255)"];
var windowH = window.innerHeight;
var windowW = window.innerWidth;

var data = !Cookies.get("data") ? [] : eval(JSON.parse(Cookies.get("data")));

if (data.length > 0) {
  for (var i = 0; i < currentLength; i++) {
    console.log(data[i]);
    var pixelData = data[i];
    placePixel(pixelData);
  }
}

for (var i = 0; i < numberOfDiv; i++) {
  var pixel = !currentLength ? i : currentLength * 1 + i;
  var pixelData = [
    chance.integer({ min: 1, max: windowH }),
    chance.integer({ min: 1, max: windowW }),
    states[Math.floor(Math.random() * states.length)],
    colors[Math.floor(Math.random() * colors.length)]
  ];
  data[pixel] = pixelData;
  placePixel(pixelData);
}

var newLength = !currentLength ? 10 : currentLength * 1 + 10;
Cookies.set("pixelLength", newLength);
Cookies.set("data", JSON.stringify(data));

function placePixel(storedData) {
  if (storedData) {
    var newDiv = document.createElement("div");
    newDiv.classList = "pixel " + storedData[2];
    newDiv.style.top = storedData[0];
    newDiv.style.left = storedData[1];
    if (storedData[2] == "stuck") newDiv.style.background = storedData[3];
    document.body.appendChild(newDiv);
  }
}

0 个答案:

没有答案