Mayx's Home Page
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.1 KiB

  1. $(function () {
  2. const urlParams = new URLSearchParams(window.location.search);
  3. const keyword = urlParams.get('kw')?.trim();
  4. if (!keyword) return;
  5. // 转义正则表达式特殊字符,避免安全问题
  6. const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  7. // 创建不区分大小写的正则表达式(全局匹配)
  8. const regex = new RegExp(`(${escapedKeyword})`, 'gi');
  9. // 递归遍历并高亮文本节点
  10. const escapeHTML = str => str.replace(/[&<>"']/g,
  11. tag => ({
  12. '&': '&amp;',
  13. '<': '&lt;',
  14. '>': '&gt;',
  15. '"': '&quot;',
  16. "'": '&#39;'
  17. }[tag] || tag));
  18. function highlightTextNodes(element) {
  19. $(element).contents().each(function () {
  20. if (this.nodeType === Node.TEXT_NODE) {
  21. const $this = $(this);
  22. const text = escapeHTML($this.text());
  23. // 使用正则替换并保留原始大小写
  24. if (regex.test(text)) {
  25. const replaced = text.replace(regex, '<mark>$1</mark>');
  26. $this.replaceWith(replaced);
  27. }
  28. } else if (
  29. this.nodeType === Node.ELEMENT_NODE &&
  30. !$(this).is('script, style, noscript, textarea')
  31. ) {
  32. highlightTextNodes(this);
  33. }
  34. });
  35. }
  36. $('section').each(function () {
  37. highlightTextNodes(this);
  38. });
  39. });
  40. function initCopyButtons() {
  41. $('.copy').remove();
  42. $('div.highlight').each(function () {
  43. var $btn = $('<button>', { class: 'copy', type: 'button', text: '📋' });
  44. $(this).append($btn);
  45. $btn.on('click', function () {
  46. var code = $btn.siblings('pre').find('code').text().trim();
  47. navigator.clipboard.writeText(code)
  48. .then(function () { $btn.text('✅'); })
  49. .catch(function () { $btn.text('❌'); })
  50. .finally(function () { setTimeout(function () { $btn.text('📋'); }, 1500); });
  51. });
  52. });
  53. }
  54. $(function() {
  55. initCopyButtons();
  56. });