时间:2023-10-02 09:24:01 | 来源:网站运营
时间:2023-10-02 09:24:01 来源:网站运营
HTML / CSS / JS 编程入门 —— 制作可切换主题的简单网页:<!--- 关联 CSS 文件的代码 ---> <link type="text/css" rel="stylesheet" href="css/style.css"/> <!--- 关联 JS 文件的代码 ---> <script type="text/javascript" src="js/script.js"></script>
在正式开始网页的编程之前,我们也可以先调整 <head> 标签中的页面信息,同时确保 CSS 和 JS 文件正确关联。 <head> <meta charset="UTF-8"> <title>Lightly 网页制作</title> <!--- 这里可以修改页面标题 ---> <link type="text/css" rel="stylesheet" href="css/style.css"/> <script type="text/javascript" src="js/script.js"></script> </head>
添加网页内容 <body> <!--- 这里的内容是评论,不会显示在网页中 ---> <!--- h1 标题 ---> <h1>网页制作指南</h1> <!--- p = paragraph 段落 ---> <p id="msg">任务清单</p> <!--- ul = unordered list 无序号列表 ---> <!--- ol = ordered list 有序号列表 ---> <!--- li 即列表中的内容 ---> <ul> <li class="list">添加可视化设计</li> <li class="list">添加浅色与深色主题</li> <li>添加切换主题功能!</li> </ul> </body>
添加好内容后,我们可以在此预览网页: /* CSS 的评论代码与 HTML 不同 */ /* 使用根目录定义颜色 */ :root { --green: #f0fff0; --white: #ffffff; --black: #000000; } * { color: var(--fontColor); }
更改字体样式 body { /* 设置背景颜色,调整文本为黑体、居中 */ font-family: SimHei; text-align: center; background: var(--bg); } ul { /* 设置 ul 文本为宋体 */ font-family: SimSun; }
为列表设置边框 /* 为 ul 添加边框 */ .feature { text-align: left; font-size: 24px; margin: auto; width: 400px; height: 200px; outline: solid 1px; /* 将列表内容居中 */ display: flex; justify-content: center; align-items: center; }
添加浅色主题 /* 添加浅色主题 */ .light-theme { color: var(--black); background: var(--green); }
在刷新网页之前,我们需要回到 .HTML 文件为 <body> 标签添加浅色主题: <body class="light-theme">
同时在 <ul> 的上下方添加 <div> 标签,注意需要为 <div> 标签添加 class: <div class="feature"> <ul> ... </ul> </div>
完成后 CSS 文件配置后,回到 .HTML 文件重新加载网页查看效果: <!--- div = division 分区 ---> <div> <button class="btn" onclick="function()">切换深色</button> </div>
接着,把 <head> 中的 script.js 关联代码移动(剪切+粘贴)到 </body> 标签结束前: <script type="text/javascript" src="js/script.js"></script> </body>
在添加切换功能前,我们需要添加并调整 CSS 的主题: /* 添加浅色主题 */ .light-theme { --bg: var(--green); --fontColor: var(--black); --btnBg: var(--black); --btnFontColor: var(--white); } /* 添加深色主题 */ .dark-theme { --bg: var(--black); --fontColor: var(--green); --btnBg: var(--white); --btnFontColor: var(--black); }
然后调整按钮设计: /* 调整按钮设计 */ .btn { position: absolute; top: 20px; left: 250px; height: 50px; width: 50px; border-radius: 50%; border: none; color: var(--btnFontColor); background-color: var(--btnBg); } /* 添加点击效果 */ .btn:focus { outline-style: none; }
最后,转到 script.js 文件并添加按钮功能: // 为 switcher 添加定义 const switcher = document.querySelector('.btn'); // 使用监听功能监听按钮动态 switcher.addEventListener('click', function() { document.body.classList.toggle('dark-theme') // 使用 if 功能实现主题切换 var className = document.body.className; if(className == "light-theme") { this.textContent = "切换深色"; } else { this.textContent = "切换浅色"; } console.log('current class name: ' + className); });
关键词:主题,简单,入门