🌈 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');
      });

      // Escape nội dung HTML để Prism.js highlight
      document.querySelectorAll('code.language-html').forEach(block => {
        block.innerText = block.innerHTML;
      });

      // Kích hoạt highlight của Prism
      if (typeof Prism !== 'undefined') {
        Prism.highlightAll();
      } else {
        console.warn("⚠️ Prism chưa được tải!");
      }

   
      // 🔘 Tạo nút Copy

      document.querySelectorAll('pre code').forEach((block) => {
        const pre = block.parentElement;
        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.innerText);
        wrapper.appendChild(btn);
      });

      // 📋 Khởi tạo Clipboard.js
      new ClipboardJS('.copy-button').on('success', function (e) {
        const btn = e.trigger;
        btn.textContent = '✅ Copied!';
        setTimeout(() => btn.textContent = '📋 Copy', 2000);
      });
   
    });
    //]]>
  </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

Bài đăng phổ biến từ blog này

🧭CRUD CHUẨN LARAVEL

🚀01 giờ học cách sử dụng Developer Console