前言
如果你需要在浏览网页时快速切换页面明暗模式,那么今天这个案例应该适合你,在网页插入明暗切换按钮,一键切换明暗模式,末尾附快捷指令体验口令。
设计思路
- 在浏览器中分享页签
- 使用执行执行 JavaScript 脚本
实现
1.接收浏览器分享的数据
2.在页签下执行脚本
var isDark = false;
// 创建一个按钮元素
var button = document.createElement("button");
// 设置按钮的文本内容
button.innerHTML = "暗模式";
// 设置样式
button.style.position = 'fixed';
button.style.top = '20px';
button.style.right = '20px';
button.style.padding = '10px 20px';
button.style.backgroundColor = '#4CAF50';
button.style.color = 'white';
button.style.cursor = 'pointer';
button.style.borderRadius = '5px';
button.style.zIndex = '2000'; // 确保按钮在最上层
var style = document.createElement("style");
style.type = "text/css";
// 添加点击事件监听器
button.onclick = function() {
if (isDark) {
button.innerHTML = "暗模式";
document.head.removeChild(style);
} else {
button.innerHTML = "明模式";
document.head.appendChild(style);
// 这里为暗模式规则
style.sheet.insertRule(`
*:not(img):not([class*="mask"]) {
color: #aaa !important;
background-color: #333 !important;
border-color: currentColor !important;
}
`, 0);
style.sheet.insertRule(`
img {
opacity: 1 !important;
}
`, 0);
}
isDark = !isDark;
};
// 将按钮添加到容器元素中
document.body.appendChild(button);
// 调用Completion以完成
completion(true);
完整示例预览
快捷指令口令
见原文:【快捷指令案例】网页明暗模式)
本文同步自微信公众号 "程序员小溪" ,这里只是同步,想看及时消息请移步我的公众号,不定时更新我的学习经验。