刷新后防止css更改

6yt4nkrj  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(252)

我在我的网站上有两个不同的主题,还有一个带有按钮的下拉菜单,您可以在其中切换主题。以下是我如何设置它的:

<script>
  function swapStyleSheet(sheet) {
    document.getElementById('pagestyle').setAttribute('href', sheet);
  }
</script>

然后,这是连接到的按钮:

<button onclick="swapStyleSheet('style-green.min.css')">Green Theme</button>

这很有效;然而,每当我点击屏幕上的刷新按钮时,它就会切换回最初附加到页面上的原始样式表。我希望它在刷新时保留它切换到的任何样式表。我该怎么做?有什么东西可以添加到我的标签中,让我存储某种类型的会话/数据吗?
谢谢

vxbzzdmp

vxbzzdmp1#

您可以使用localstorage来实现这一点;

<script>
 function swapStyleSheet(sheet) {
   localStorage.setItem('style', sheet);
   document.getElementById('pagestyle').setAttribute('href', sheet);
 }

 function applyStyleSheet() {
   // restore style
   const sheet = localStorage.getItem('style') || 'style-green.min.css';
   document.getElementById('pagestyle').setAttribute('href', sheet);
 }

 applyStyleSheet();

</script>
agxfikkp

agxfikkp2#

您可以存储 href 在里面 localStorage .
要保存它,您可以使用:

localStorage.setItem('csshref', href);

在页面加载时,您可以执行以下操作:

swapStylesheet(localStorage.getItem('csshref'))

相关问题