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.

67 lines
2.3 KiB

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