Extend Selection

按F2扩展当前选中的文字范围

  1. // ==UserScript==
  2. // @name Extend Selection
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1
  5. // @description 按F2扩展当前选中的文字范围
  6. // @match *://*/*
  7. // @grant none
  8. // @license MIT
  9. // ==/UserScript==
  10.  
  11. (function() {
  12. 'use strict';
  13.  
  14. // 处理键盘按下事件
  15. document.addEventListener('keydown', function(e) {
  16. if (e.key === "F2") {
  17. const selection = window.getSelection();
  18. if (selection.rangeCount > 0) {
  19. const range = selection.getRangeAt(0);
  20. const startContainer = range.startContainer;
  21. const endContainer = range.endContainer;
  22.  
  23. // 向上扩展选区
  24. if (startContainer.parentNode) {
  25. range.setStartBefore(startContainer.parentNode);
  26. }
  27.  
  28. // 向下扩展选区
  29. if (endContainer.parentNode) {
  30. range.setEndAfter(endContainer.parentNode);
  31. }
  32.  
  33. // 更新选区
  34. selection.removeAllRanges();
  35. selection.addRange(range);
  36. }
  37. }
  38. });
  39. })();