【问题标题】:How to keep css style changes in JavaScript with sessionStorage如何使用 sessionStorage 保持 JavaScript 中的 css 样式更改
【发布时间】:2020-10-12 01:41:39
【问题描述】:

我正在尝试制作一个在块和无之间切换 CSS 显示属性的按钮。我正在尝试这样做,以便用户可以打开和关闭背景颜色,然后在页面之间移动时保留选择。更尴尬的是,我只能使用 inline-CSS 和 vanilla JavaScript 来做到这一点。

到目前为止,我已经设法让 display 属性切换,但我不知道如何实现 sessionStorage。我已经尝试过一百万种不同的方式。下面的例子是我最近的尝试。

任何帮助将不胜感激:)

<div onchange="colours()" id='red' width='100%' height='auto' style="background-color:red; padding: 20%; display:block;">
  
</div>
<button  id="button" style='font-size: 200px;'>test</button>
var e = document.getElementById('red');

() => {

    if (sessionStorage.getItem('divColor') === '1'){
        e.style.display = "none";
    }
  else{
    e.style.display = "block";
  }
}



document.getElementById('button').addEventListener('click', function() {
  if (e.style.display === 'block') { 
  e.style.display = 'none';
     sessionStorage.setItem("divColor", 1);
  } else { 
  e.style.display = 'block';
  }
});

【问题讨论】:

    标签: javascript css session-storage


    【解决方案1】:

    您可以使用 cookie 存储: 解释: 在函数中更改背景后将其保存在cookie中并设置cookie过期日期,过期日期可能是一天或任何时间,如果不提示客户端更改页面背景,请始终检查cookie是否设置,并且一旦设置了cookie,使用cookie中存储的颜色值来设置页面背景,一旦浏览器存储了cookie,它将始终可用,我认为这是在网站。 希望这个解释有用

    【讨论】:

      【解决方案2】:

      我发现了我的问题!花了整个周末,但我做到了(我是 JS 新手,所以小胜利意味着很多)。

      <button id="button" style="padding: 20px";>test</button>
        
      <p id="text" style="font-size:200px; padding: 0; margin: 0; text-transform: uppercase; background-color:red;">change me</p>
      
      var button = document.getElementById('button');
      
      var text = document.getElementById('text');
      
      var key = sessionStorage.getItem ('key');
      
      var obj = JSON.parse(key);
      
      
      if (key)
        {text.style.background = obj};
      
      button.addEventListener('click', textChange);
      
      function textChange (test) {
        if (text.style.backgroundColor === 'red') {
          text.style.backgroundColor = 'blue';
          sessionStorage.setItem ('key', JSON.stringify (text.style.backgroundColor));
        } else {
          text.style.backgroundColor = 'red';
           sessionStorage.removeItem ('key');
        } 
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-09
        • 1970-01-01
        • 1970-01-01
        • 2013-09-02
        相关资源
        最近更新 更多