gpt4 book ai didi

javascript - 有没有一种方法可以根据不同页面的样式表更改页面的样式表?

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:42 25 4
gpt4 key购买 nike

我正在制作一个网页,其中包含用于将主题从浅色更改为深色并返回首页的按钮。但是,如果我点击进入另一个页面,我希望保留主题。

有没有办法告诉浏览器根据用户使用的是浅色还是深色主题动态选择 css 文件?

我在首页上的内容供引用:

Javascript:

function swapStyleSheet(sheet, text){
//variables to access elements in the DOM
var styleSheet = document.getElementById('pagestyle');
var defaultText = document.getElementById('styleSwitchText');

styleSheet.setAttribute('href', sheet); //changes the stylesheet
defaultText.style.display = "none"; //hides initial text

//creates p element and appends text parameter to it
var pElement = document.createElement('p');
var textnode = document.createTextNode(text);
pElement.appendChild(textnode);

var item = document.getElementById('swapStyleButtons');
//replaces the text node in the p each time button is clicked
item.replaceChild(pElement, item.childNodes[0]);
}

html:

<div id="swapStyleButtons">
<p id="styleSwitchText">Don't like the style? Try Night Mode!</p>
<button id='night' onclick='swapStyleSheet("dark.css", "Think Night Mode sucks? Switch back!")'>Night</button>
<button id='default' onclick='swapStyleSheet("recipes.css", "Liked it better before? Try Night Mode!")'>Default</button>
</div>

这在首页上非常有效。我可以对其他页面重复这个过程,但用户必须在每个页面上按下按钮,这显然有点烦人。

1 个 html 页面可以用这种方式与另一个 html 页面通信吗?

最佳答案

使用 HTML5,您可以使用 HTML 本身存储数据,而无需使用其他语言。

function setColorTheme(curColorTheme)
{
if(typeof(Storage) !== "undefined") {
localStorage.setItem("colorTheme", curColorTheme);
} else {
// Backup cookie Support
}
}

function getColorTheme()
{
if(typeof(Storage) !== "undefined") {
return localStorage.getItem("colorTheme");
} else {
// Backup cookie Support
}
}

这是一个教程:

http://www.w3schools.com/html/html5_webstorage.asp

关于javascript - 有没有一种方法可以根据不同页面的样式表更改页面的样式表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36663361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com