
highlight.js 默认只在页面加载时自动高亮已存在的代码块;对于通过 fetch 异步插入的 github 源码,需手动调用 `hljs.highlightelement()` 触发高亮,否则无法生效。
要在网页中正确高亮从 GitHub(如 raw.githubusercontent.com)动态获取的代码(例如 PowerShell 脚本),关键在于理解 Highlight.js 的执行时机:它默认在 DOM 加载完成时通过 hljs.highlightAll() 扫描并处理所有
<code> 元素。而你使用 fetch() 获取内容并设置 textContent 是<strong>异步操作</strong>,发生在 highlightAll() 之后,因此新插入的代码不会被自动识别。</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/1837" title="Mokker AI"><img
src="https://img.php.cn/upload/ai_manual/000/969/633/68b6c9b25e117919.png" alt="Mokker AI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/1837" title="Mokker AI">Mokker AI</a>
<p>AI产品图添加背景</p>
</div>
<a href="/ai/1837" title="Mokker AI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p>✅ 正确做法是:在代码写入 DOM 后,<strong>显式调用 hljs.highlightElement(element)</strong> 对目标 <code> 元素进行单次高亮。</p><h3>✅ 完整工作示例</h3><pre class="brush:php;toolbar:false;"><!DOCTYPE html>
<html>
<head>
<!-- 样式必须引入(推荐原子主题) -->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/highlightjs/highlight.js@11.9.0/build/styles/atom-one-dark-reasonable.min.css">
</head>
<body>
<!-- 必须使用 <pre class="brush:php;toolbar:false;"><code> 结构,且指定 language 类(可选但推荐) -->
<pre class="brush:php;toolbar:false;"><code id="code" class="powershell"></code>
<script src="https://<a%20style=" color: text-decoration:underline title="cdn" href="https://www.php.cn/zt/19618.html" target="_blank">cdn.jsdelivr<a style="color:#f60; text-decoration:underline;" title= ".net" href="https://www.php.cn/zt/64958.html" target="_blank">.net/gh/highlightjs/highlight.js@11.9.0/build/highlight.min.js"></script><script src="https://cdnjs.cloudflare.com/<a%20style=" color: text-decoration:underline title="ajax" href="https://www.php.cn/zt/15849.html" target="_blank">ajax/libs/highlight.js/11.9.0/languages/powershell.min.js"></script><script>
// 动态加载 GitHub 原始文件内容
fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1")
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
return response.text();
})
.then(data => {
const codeEl = document.getElementById('code');
codeEl.textContent = data; // ⚠️ 不要用 innerHTML,避免 XSS
codeEl.className = 'language-powershell'; // 显式声明语言(提升检测准确率)
// ✅ 关键:手动触发高亮
hljs.highlightElement(codeEl);
})
.catch(err => {
console.error("代码加载失败:", err);
document.getElementById('code').textContent = `// 加载错误:${err.message}`;
});
</script>









