CSS切换开关无法生效:自定义Google页面样式不显示问题求助
问题分析与修复方案
你的代码存在以下几个关键问题,导致开关切换后样式无法正常生效:
1. 事件绑定时机不对且未做元素存在性检查
window.onload需要等待页面所有资源加载完成才会执行,可能此时目标开关按钮togBtn还未被渲染到DOM中,document.getElementById("togBtn")会返回null,调用addEventListener直接抛出错误,导致整个切换逻辑瘫痪。
2. removeCSS函数缺乏容错处理
当开关未开启(customStyle未赋值)时点击关闭按钮,或重复点击关闭按钮,customStyle可能为undefined或已被移除的DOM元素,调用remove()会抛出错误,中断后续操作。
3. 重复创建style元素导致样式泄漏
多次点击开启按钮时,每次都会新建<style>元素并添加到页面,但旧的style元素不会被移除,既会造成样式叠加冲突,还会让customStyle变量被新元素覆盖,旧元素无法被清理。
修复后的代码
// 获取当前站点域名 const site = window.location.hostname; // 保存style元素引用,初始化为null let customStyle = null; // 添加自定义样式函数 const Add_Custom_Style = (css) => { // 先移除已存在的样式,避免重复创建 if (customStyle) { Remove_Custom_Style(); } // 创建新的style元素并赋值 customStyle = document.createElement("style"); customStyle.innerHTML = css; document.head.appendChild(customStyle); }; // 移除自定义样式函数 const Remove_Custom_Style = () => { // 仅当元素存在时执行移除操作 if (customStyle && customStyle.parentNode) { customStyle.parentNode.removeChild(customStyle); customStyle = null; // 重置引用 } }; // 应用Google页面自定义样式 function changeCSS() { if (site.includes("google.com")) { Add_Custom_Style(` @import url('https://fonts.googleapis.com/css2?family=Advent+Pro:wght@300&display=swap'); * { font-family: 'Advent Pro', sans-serif !important; color: #fff !important; } a { color: #b0dff4 !important; font-size: 140%; } h1, h2, h3, h4, h5, h6 { color: #b0dff4 !important; } `); } } // 切换逻辑:使用DOMContentLoaded确保元素已加载 document.addEventListener("DOMContentLoaded", function() { const cssToggleBtn = document.getElementById("togBtn"); // 检查按钮是否存在,避免报错 if (!cssToggleBtn) return; cssToggleBtn.addEventListener("change", function() { if (this.checked) { changeCSS(); } else { Remove_Custom_Style(); } }); // 可选:页面加载时根据开关状态初始化样式 if (cssToggleBtn.checked) { changeCSS(); } });
额外说明
- 用
DOMContentLoaded替代window.onload,它会在DOM渲染完成后立即执行,无需等待图片、字体等资源加载,更适合绑定DOM元素事件。 - 新增重复创建style元素的防护逻辑,每次开启样式前先清理旧元素。
- 给移除样式的函数增加了存在性检查,避免空引用错误。
- 如果开关按钮是动态生成的(比如通过JS添加到页面),建议使用事件委托绑定事件,例如监听按钮父元素的
change事件,确保事件能正常触发。
内容的提问来源于stack exchange,提问作者itsfrxst
相关产品推荐
相关产品推荐

