console
(() => {
if (document.createElement("STYLE").scoped !== undefined) {
return;
}
document.createElement("STYLE").__proto__.scoped = false;
function updateSelector(selector, scope) {
return selector.split(",").map(x => x.replace(/((?<=^\s*)\s|^)([\S])/, "$1" + scope + " $2")).join(",");
}
function updateCss(css, scope) {
css = css.replace(/("[^"]*")|('[^']*')/g, x => x.charAt(0) + encodeURIComponent(x.slice(1, -1)) + x.charAt(0));
css = css.replace(/[^{}]+{/g, x => updateSelector(x, scope));
css = css.replace(/("[^"]*")|('[^']*')/g, x => x.charAt(0) + decodeURIComponent(x.slice(1, -1)) + x.charAt(0));
return css;
}
function updateStyle(style) {
if (!style
|| style.parentElement == null
|| style.parentElement == document.head
|| style.parentElement == document.body
|| !style.hasAttribute("scoped")
|| style.scoped === true) {
return;
}
style.scoped = true;
const scope = ("_" + (Math.random() * 100000000).toString("36")).replace('.', '');
style.parentElement.setAttribute(scope, '');
style.textContent = updateCss(style.textContent, "[" + scope + "]");
}
const callback = function (mutationsList) {
if (mutationsList.length == 0) {
return;
}
for (const mutation of mutationsList) {
for (const node of mutation.addedNodes) {
if (node.nodeName === "STYLE") {
updateStyle(node);
}
}
}
};
const observer = new MutationObserver(callback);
const config = { childList: true, subtree: true };
observer.observe(document, config);
setInterval(() => callback(observer.takeRecords()), 100);
[...document.getElementsByTagName('style')].forEach(x => updateStyle(x));
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<style type="text/css">
h1 {
color: green;
}
p {
color: black;
}
</style>
</head>
<body>
<div>
<style type="text/css" scoped>
h1 {
color: red;
}
p {
color: blue;
}
</style>
<h1>这个标题是红色的</h1>
<p>这个段落是蓝色的。</p>
</div>
<h1>这个标题是绿色的</h1>
<p>这个段落是黑色的。</p>
</body>
</html>