代码实现参考:https://highlightjs.org/
实现原理,基于link标签的disable。
演示代码:
index.html
<!DOCTYPE /> <html> <head> <meta charset="utf-8"> <title>setTimeout</title> <link class="codestyle" rel="prefetch alternate stylesheet" href="./c1.css"> <link class="codestyle" rel="prefetch alternate stylesheet" href="./c2.css"> <script type="text/javascript"> //link 切换 var style = 'c1'; function initSnippet() { for (let link of document.querySelectorAll('.codestyle')) { link.rel = 'stylesheet'; link.disabled = !link.href.match(style + '\.css$'); //正则中"."需要转义,加个"",""又需要转义 } } addEventListener('load', initSnippet); setTimeout(function () { style = "c2"; initSnippet(); }, 1000) </script> </head> <body> <div style=" 100px;height: 100px;"></div> </body> </html>
c1.css
div { background-color: #f00; }
c2.css
div { background-color: #0f0; }