简体   繁体   English

我希望通过在脚本中添加 Cookie 代码进行浏览器刷新时不更改当前设置?

[英]I Want The Current Setting Not To Change When Browser Refresh Is Made By Adding Cookie Codes In The Script?

I placed the following script code into the night mode button with the help of onclick = "swap ()" .我在onclick = "swap ()"的帮助下将以下脚本代码放入夜间模式按钮。 My goal: When the page is in dark mode, the other logo is active.我的目标:当页面处于黑暗模式时,另一个徽标处于活动状态。 When it's daytime mode, get another logo.当它是白天模式时,获得另一个标志。 But the problem is that when I do F5 on the page while in dark mode, the logo reverts to its original state even though the page remains in dark mode.但问题是,当我在黑暗模式下在页面上执行 F5 时,即使页面仍处于黑暗模式,徽标也会恢复为其原始 state。 Is it possible to edit the script code to help it stay in the cache in the browser?是否可以编辑脚本代码以帮助它保留在浏览器的缓存中?

 var shown = 'header_logo_ayar_1'; function swap() { if (shown === 'header_logo_ayar_1') { document.getElementById('header_logo_2').style.display = ""; document.getElementById('header_logo_1').style.display = "none"; shown = 'header_logo_ayar_2'; } else { document.getElementById('header_logo_1').style.display = ""; document.getElementById('header_logo_2').style.display = "none"; shown = 'header_logo_ayar_1'; } };
 <a id="header_logo_1" href="#" title=""> <figure><img src="img/logo_1.webp" alt="" width="" height=""></figure> </a> <a id="header_logo_2" href="#" title="" style="display:none;"> <figure><img src="img/logo_2.webp" alt="" width="" height=""></figure> </a>

I got this working example from here: https://jsfiddle.net/v2k3rzge/我从这里得到了这个工作示例: https://jsfiddle.net/v2k3rzge/

I edited my own work.我编辑了自己的作品。

If there are friends who can help on the subject, I ask them to answer.如果有朋友可以在这个问题上提供帮助,我请他们回答。 Thanks in advance...提前致谢...

Okay, you can use localStorage to get and set items.好的,您可以使用localStorage来获取和设置项目。

var shown;
if (localStorage.getItem("shown") === null) {
  shown = "header_logo_ayar_1";
} else {
  shown = localStorage.getItem("shown");
}
// Or you could do this (with more advanced syntax)
var shown = (localStorage.getItem("shown") ?? "header_logo_ayar_1");


function swap() {
  // ...

  localStorage.setItem("shown", shown);
}

localStorage doesn't work in Stack Snippets, so try this JSitor link . localStorage在 Stack Snippets 中不起作用,所以试试这个 JSitor 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM