我有这个功能可以用一个按钮打开和关闭黑暗模式。 它检查是否已将dark.css样式表添加到站点中,如果是,则将其删除。如果没有dark.css,它会加载它并将其附加到头部。
现在我想将此信息存储在localStorage中,以便浏览器记住是否应该加载dark.css。
$(function() {
$('#toggler').click(function(){
if ($('link[href*="css/dark.css"]').length) {
$('link[href*="css/dark.css"]').remove();
}
else {
var lightMode = document.createElement('link');
darkMode.rel="stylesheet";
darkMode.href="css/dark.css";
document.getElementsByTagName('head')[0].appendChild(darkMode);
}
});
})
答案 0 :(得分:0)
您所要做的就是在jQuery函数中检查localStorage。最好在函数的早期(因此,如果你在其他地方有一些强化代码,那么DOM会快速更新),尽管不是必需的。
$( function () {
function appendDarkMode() {
var darkMode = document.createElement( 'link' );
darkMode.rel = 'stylesheet';
darkMode.href = 'css/dark.css';
document.getElementsByTagName( 'head' )[ 0 ].appendChild( darkMode );
}
// This is run when page is first loaded.
if ( localStorage ) {
var useDarkMode = localStorage.getItem( 'useDarkMode' );
// The boolean we set in the click handler will become a string.
useDarkMode === 'true' ? appendDarkMode() : localStorage.setItem( 'useDarkMode', false );
}
// Theme click handler.
$( '.toggler' ).on( 'click', function ( e ) {
var $darkModeLink = $( 'link[href*="css/dark.css"]' );
$darkModeLink.length ? $darkModeLink.remove() : appendDarkMode();
if ( localStorage ) {
// Note that we're inverting the value here. By the time this
// is run, we will have changed whether or not `dark.css` is
// on the page. Which is opposite the initial value of
// `$darkModeLink`.
localStorage.setItem( 'useDarkMode', !$darkModeLink.length );
}
} );
} );
答案 1 :(得分:0)
虽然我不认为你的方法是最好的(加载这种方式可能产生一个'flash'的不正确样式的内容取决于你放置你的JS逻辑的位置),这是我的解决方案(没有测试,但应该工作):
仅供参考:您需要检查localStorage
可用性或滚动pollyfill。见Mozilla Docs
$(function() {
var themes = {
light: 'light',
dark: 'dark'
};
var currentTheme = themes.light; // default to light
function changeTheme(theme) {
if (!theme || !themes[theme]) return;
setTheme(theme);
Object.keys(themes).forEach(function(t) {
var linkEl = $('link[href*="css/' + t + '.css"]');
if (linkEl.length && t !== theme) {
linkEl.remove();
}
});
}
function setTheme(theme) {
if (!theme || !themes[theme]) return;
var linkEl = document.createElement('link');
linkEl.rel="stylesheet";
linkEl.href="css/" + theme + ".css";
document.getElementsByTagName('head')[0].appendChild(linkEl);
if (localStorage) {
localStorage.setItem('theme', theme);
}
currentTheme = theme;
}
if (localStorage) {
var theme = localStorage.getItem('theme');
changeTheme(theme);
} else {
changeTheme(currentTheme);
}
$('#toggler').click(function(){
switch (currentTheme) {
case themes.light:
changeTheme(themes.dark);
break;
case themes.dark:
default:
changeTheme(themes.light);
break;
}
});
})