[英]How do i use cookies to store a different theme colour so it changes on all pages on my site not just the homepage?
I am trying to store my theme colour in a cookie so when i click a button it changes the theme on my homepage but it doesn't change it for my other pages. 我正在尝试将主题颜色存储在cookie中,因此当我单击按钮时,它将更改主页上的主题,但不会更改其他页面上的主题。
JavaScript code: - scroll down to see the new code. JavaScript代码:-向下滚动以查看新代码。
$(document).ready(function () {
$("button").click(function () {
document.cookie = "theme=grey";
return false;
});
});
let themeColor = document.cookie;
html code: this is on my master page. html代码:这在我的主页上。
<div id="footer">
<div id="footer_content">
<img src="Images/fasthosts2.png" alt="Fasthostslogo" width="150" height="50" />
<div class="foot"></div>
<button> Change Theme</button>
</div>
</div>
links: 链接:
<script src="ThemeChanger.js"></script>
New and better code but still doesn't work on all pages. 新的更好的代码,但仍不能在所有页面上使用。 JS:
JS:
$(document).ready(function () {
$('#ChangeTheme').click(function () {
document.body.style.setProperty("--color1", "orange")
document.body.style.setProperty("--color2", "red")
document.body.style.setProperty("--color3", "white")
return false;
});
});
CSS: CSS:
:root {
--color1: #3366cc;
--color2: #2d2d2d;
--color3: white;
}
#header {
background-color: #3366cc;
height: 110px;
position: fixed;
top: 0;
width: 100%;
display: table;
border-bottom: 5px solid #0099ff;
border-top: 5px solid #2d2d2d;
background: linear-gradient(var(--color2), var(--color1));
}
#footer {
background-color: darkblue;
height: 150px;
position: fixed;
bottom: 0;
width: 100%;
border-top: 5px solid #0099ff;
background: linear-gradient(var(--color1), var(--color2));
}
HTML: HTML:
<asp:Button ID="ChangeTheme" runat="server" Text="Change Theme" Width="110px" CausesValidation="false" BackColor="#99CCFF" BorderColor="#000066" BorderStyle="Solid" />
Welcome to stack overflow 欢迎堆栈溢出
You need to change your code to 您需要将代码更改为
$("button").click(function () {
document.cookie = "theme=grey;path=/";
return false;
});
By adding path=/
you tell the browser to save the cookie on domain level. 通过添加
path=/
您告诉浏览器将cookie保存在域级别。 Otherwise the browser will create the cookie for the specific page you are clicking button on. 否则,浏览器将为您单击的特定页面创建cookie。
You can use localStorage
. 您可以使用
localStorage
。 I think its the preferred way to go. 我认为这是首选的方式。
To save or update use : 要保存或更新使用:
localStorage.setItem('theme','value');
To get the Value: 要获得价值:
localStorage.getItem('theme');
To clear: 清除:
localStorage.clear()
You need to make sure that the other pages also read the cookie value and change the style accordingly. 您需要确保其他页面也读取cookie值并相应地更改样式。 It would be helpful if you added all of your code, like the bits that use the variable themeColor .
如果您添加了所有代码,例如使用变量themeColor的位,将很有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.