Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

How to create and use a Syntax Highlighter with JavaScript?


เพื่อสร้างและใช้ Syntax Highlighter โค้ดมีดังนี้

ตัวอย่าง

<!DOCTYPE html> <html> <head> <style>    body {       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    }    .colorLinks {       color: rgb(131, 44, 212);       text-decoration: none;       font-size: 20px;       font-weight: bold;    }    .setColor {       margin: 20px;       padding: 10px;       border: none;       font-size: 18px;       background-color: rgb(226, 43, 89);       color: white;    } </style> </head> <body> <h1>Syntax Highlighting example</h1> <div class="CodeDiv"> <a href="https://www.google.com">Go to google.com</a> <a href="https://www.facebook.com">Go to facebook.com</a> </div> <button class="setColor" onclick="highlightLinks()">Click Here</button> <h2>Click the above button to highlight the links</h2> <script>    var anchrorRg = /[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g;    function highlightLinks() {       var text = document.querySelector(".CodeDiv").innerHTML;       text = text.replace(anchrorRg, function() {          function check(arguments) {             let tempArr = [];             tempArr.push(Array.prototype.slice.call(arguments, 2, 4));             return `<a class="colorLinks" href=${tempArr[0][0]}>${tempArr[0][1]}</a><br>`;          }          return check(arguments);       });       document.querySelector(".CodeDiv").innerHTML = text;    } </script> </body> </html>

ผลลัพธ์

โค้ดข้างต้นจะสร้างผลลัพธ์ดังนี้บนขนาดหน้าต่างมากกว่า 700px -

How to create and use a Syntax Highlighter with JavaScript?

เมื่อคลิกปุ่ม "Click Here" -

How to create and use a Syntax Highlighter with JavaScript?