中键选择文本

用鼠标中键选择文本

  1. // ==UserScript==
  2. // @name select text by middle button
  3. // @name:zh-CN 中键选择文本
  4. // @namespace http://tampermonkey.net/
  5. // @version 0.1
  6. // @description select the text by middle button
  7. // @description:zh-CN 用鼠标中键选择文本
  8. // @author Harytfw
  9. // @match http://*/*
  10. // @match https://*/*
  11. // @grant none
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16.  
  17. var x1=0.0,y1=0.0;
  18. const MIN_MOVEMENT = 10;
  19. const se = document.getSelection();
  20. const LEFT_BUTTON = 0,
  21. MIDDLE_BUTTON = 1;
  22. const STATE_INIT = 0,
  23. STATE_READY = 1,
  24. STATE_WORKING = 2,
  25. STATE_FINISH = 3;
  26. let state = STATE_INIT;
  27.  
  28. function mousedown(e) {
  29. if(e.button!==MIDDLE_BUTTON){
  30. return;
  31. }
  32. x1=e.clientX;
  33. y1=e.clientY;
  34. const range = document.caretPositionFromPoint(x1, y1);
  35. se.setBaseAndExtent(range.offsetNode,range.offset,range.offsetNode,range.offset);
  36. state = STATE_READY;
  37. }
  38. var x2=0.0,y2=0.0;
  39. function mouseup(e){
  40. if(e.button===MIDDLE_BUTTON){
  41. if(state===STATE_WORKING) state=STATE_FINISH;
  42. else state=STATE_INIT;
  43. }
  44. }
  45. function mousemove(e){
  46. if(state===STATE_INIT)return;
  47. x2=e.clientX;
  48. y2=e.clientY;
  49. if(Math.hypot(x1-x2,y1-y2)>=MIN_MOVEMENT){
  50. if(state===STATE_WORKING || state===STATE_READY){
  51. const range = document.caretPositionFromPoint(x2, y2);
  52. if(se.anchorNode!== null)se.extend(range.offsetNode,range.offset);
  53. state=STATE_WORKING;
  54. }
  55. }
  56. else{
  57. state=STATE_READY;
  58. }
  59. }
  60. function click(e){
  61. if(e.button===MIDDLE_BUTTON && state==STATE_FINISH){
  62. e.preventDefault();
  63. }
  64. state=STATE_INIT;
  65. }
  66. document.addEventListener('mouseup', mouseup);
  67. document.addEventListener('mousedown', mousedown);
  68. document.addEventListener('mousemove', mousemove);
  69. document.addEventListener('click', click);
  70.  
  71. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址