将 CSS 或 HTML 存储在 localStorage 中



我有这个功能可以用一个按钮打开和打开暗模式。 它检查深色.css样式表是否已添加到站点,如果是,则将其删除。如果没有黑暗.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);
}
});
})

您所要做的就是在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  );
}
} );
} );

虽然我不认为你的方法是最好的(根据你放置JS逻辑的位置,以这种方式加载可能会产生样式不正确的内容的"flash"),这是我的解决方案(未经测试,但应该可以工作):

仅供参考:您需要检查localStorage可用性或滚动 pollyfill。查看 Mozilla 文档

$(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;
}
});
})

最新更新