🌈 Tự Động Highlight Code Trong Blogger
Phần style
pre code {
white-space: pre-wrap;
word-break: break-word;
}
.code-wrapper {
position: relative;
}
.copy-button {
position: absolute;
top: 8px;
right: 8px;
background: #444;
color: #fff;
border: none;
font-size: 0.75rem;
padding: 4px 8px;
border-radius: 6px;
cursor: pointer;
opacity: 0.7;
z-index: 9;
}
.copy-button:hover {
opacity: 1;
}
Chèn trước thẻ đóng head
Code nhiều dòng hay 01 dòng xài giống nhau:
const msg = "Xin chào Tiến sĩ M!";
console.log(msg);
Code 01 dòng:
document.querySelector()
Thẻ nào quá phức tạp thì xài như sau:
<pre class="language-js" data-keep-markup> <code> Nội dung... </code></pre>
Chèn trước thẻ đóng body
<b:if cond='true'>
<script type='text/javascript'>
//<![CDATA[
document.addEventListener("DOMContentLoaded", function () {
console.log("🎯 Script ai-table đang chạy");
// Né các bảng đã có DataTable
document.querySelectorAll('table:not(.dataTable)').forEach(table => {
if (table.hasAttribute('border')) {
table.removeAttribute('border');
}
table.classList.add('ai-table', 'table-hover-combo');
});
// 🔘 Tạo nút Copy
document.querySelectorAll('pre code').forEach((block) => {
const pre = block.parentElement;
if (pre.parentElement.classList.contains('code-wrapper')) {
return;
}
pre.classList.add('line-numbers');
// Ép tất cả thành JavaScript
block.className = 'language-js';
const wrapper = document.createElement('div');
wrapper.className = 'code-wrapper';
pre.parentNode.insertBefore(wrapper, pre);
wrapper.appendChild(pre);
const btn = document.createElement('button');
btn.className = 'copy-button';
btn.innerText = '📋 Copy';
// ⚠️ Dùng innerText thay vì innerHTML để lấy nội dung thực tế
btn.setAttribute('data-clipboard-text', block.textContent);
wrapper.appendChild(btn);
});//END querySelectorAll('pre code')
// 📋 Khởi tạo Clipboard.js
if (typeof ClipboardJS !== 'undefined') {
new ClipboardJS('.copy-button').on('success', function (e) {
const btn = e.trigger;
btn.textContent = '✅ Copied!';
setTimeout(() => btn.textContent = '📋 Copy', 2000);
});
}
if (typeof Prism !== 'undefined') {
Prism.highlightAll();
}
});//END "DOMContentLoaded", function ()
//]]>
</script>
</b:if>
Các thẻ html hay bị lỗi thì sửa lại:
<pre class="language-markup">
<code>
Nội dung...
</code>
</pre>
Nhận xét
Đăng nhận xét