如何通过jQuery在#btns的CSS代码被修改时重定向网页
解决CSS修改时自动重定向的问题
你之前的代码出现误触发,核心原因是模板字符串里的st包含额外缩进和换行,和#styleTag里的文本格式不一致,导致即使CSS内容没改,字符串对比也会不相等。下面给你两种可行的解决方案:
方案一:标准化字符串格式后对比
通过统一处理字符串的空格、换行,消除格式差异,同时监听style标签的内容变化实现实时检测:
<!DOCTYPE html> <html> <head> <style id="styleTag"> #btns { background: #00c9c9!important; border: none!important; padding: 12px 16px!important; color: #fff!important; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { // 定义标准CSS内容并标准化处理 var originalCss = `#btns { background: #00c9c9!important; border: none!important; padding: 12px 16px!important; color: #fff!important; }`.replace(/\s+/g, ' ').trim(); // 获取当前style内容并标准化 var currentCss = $("#styleTag").text().replace(/\s+/g, ' ').trim(); // 页面加载时检测 if (originalCss !== currentCss) { window.location.href = "https://www.google.com/"; } // 监听style标签内容变化,实时检测 var observer = new MutationObserver(function(mutations) { mutations.forEach(function() { var updatedCss = $("#styleTag").text().replace(/\s+/g, ' ').trim(); if (originalCss !== updatedCss) { window.location.href = "https://www.google.com/"; } }); }); observer.observe(document.getElementById('styleTag'), { childList: true, characterData: true, subtree: true }); }); </script> </head> <body> <button id="btns"> A Button </button> </body> </html>
原理:用replace(/\s+/g, ' ')把所有连续空格、换行、制表符替换成单个空格,再trim去除首尾空格,确保只要CSS规则内容一致,字符串就相等。
方案二:检测元素计算样式(更可靠)
通过获取按钮实际生效的样式,对比预期值,能检测所有导致按钮样式变化的情况(包括style标签修改、外部样式覆盖等):
<!DOCTYPE html> <html> <head> <style id="styleTag"> #btns { background: #00c9c9!important; border: none!important; padding: 12px 16px!important; color: #fff!important; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { // 定义预期的生效样式(注意计算值格式,比如颜色会转成rgb) var expectedStyles = { background: "rgb(0, 201, 201)", border: "none", padding: "12px 16px", color: "rgb(255, 255, 255)" }; function checkStyles() { var btn = document.getElementById('btns'); var computedStyle = window.getComputedStyle(btn); var isModified = false; // 逐一对比关键样式属性 for (var prop in expectedStyles) { if (computedStyle[prop] !== expectedStyles[prop]) { isModified = true; break; } } if (isModified) { window.location.href = "https://www.google.com/"; } } // 页面加载时检测 checkStyles(); // 监听style标签变化 var observer = new MutationObserver(checkStyles); observer.observe(document.getElementById('styleTag'), { childList: true, characterData: true, subtree: true }); // 可选:定时检测(防止外部样式表动态修改) setInterval(checkStyles, 1000); }); </script> </head> <body> <button id="btns"> A Button </button> </body> </html>
原理:window.getComputedStyle能获取元素实际生效的样式,不管样式来自哪里,只要和预期值不符就触发重定向。
方案对比
- 字符串对比:只检测指定style标签内的#btns规则,适合只关注该标签修改的场景。
- 计算样式对比:覆盖所有可能影响按钮样式的修改,更全面,但需要注意计算值的格式匹配。
内容的提问来源于stack exchange,提问作者Its Md Ibrahim
相关产品推荐
相关产品推荐

