本地存储(Local Storage) 是一种在客户端浏览器中存储数据的方式,它允许网站保存大量数据而不影响网站的性能。与Cookie不同,本地存储中的数据没有过期时间,数据会一直保留直到被显式删除。
样式表(CSS) 是用于描述HTML文档外观和格式的样式语言。通过切换不同的样式表,可以实现网站的不同主题或布局。
类型:
style
属性。<head>
部分使用<style>
标签。<link>
标签引入外部的CSS文件。应用场景:
以下是一个简单的示例,展示如何使用本地存储在两个外部样式表之间切换:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Style Switcher</title>
<link id="theme-style" rel="stylesheet" href="light-theme.css">
</head>
<body>
<button onclick="switchTheme()">Switch Theme</button>
<script src="script.js"></script>
</body>
</html>
function switchTheme() {
const currentTheme = localStorage.getItem('theme');
let newTheme;
if (currentTheme === 'dark') {
newTheme = 'light';
document.getElementById('theme-style').href = 'light-theme.css';
} else {
newTheme = 'dark';
document.getElementById('theme-style').href = 'dark-theme.css';
}
localStorage.setItem('theme', newTheme);
}
// Check local storage on page load to set the correct theme
window.onload = function() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
document.getElementById('theme-style').href = `${savedTheme}-theme.css`;
}
};
/* light-theme.css */
body {
background-color: white;
color: black;
}
/* dark-theme.css */
body {
background-color: black;
color: white;
}
问题1:样式表切换后没有立即生效
问题2:本地存储数据丢失
通过以上方法,可以实现一个简单且可靠的样式表切换功能,提升用户体验和应用的可定制性。
领取专属 10元无门槛券
手把手带您无忧上云