calculation of selection length

it displays the length of the selected character string to the calculated screen.

このスクリプトの質問や評価の投稿はこちら通報はこちらへお寄せください。
  1. // ==UserScript==
  2. // @name calculation of selection length
  3. // @namespace http://www.sharkpp.net/
  4. // @version 0.1
  5. // @description it displays the length of the selected character string to the calculated screen.
  6. // @author sharkpp
  7. // @copyright 2015, sharkpp
  8. // @license MIT License
  9. // @include http://*/*
  10. // @include https://*/*
  11. // ==/UserScript==
  12. (function () {
  13. // simply i18n load string
  14. var _ = function(res, key) {
  15. var browserLang = (window.navigator.userLanguage || window.navigator.language ||
  16. window.navigator.browserLanguage).substr(0,2);
  17. var s = '', l = null, k;
  18. for (k in res) {
  19. if (browserLang == k || !l)
  20. l = k;
  21. }
  22. if (undefined != res[l][key]) {
  23. s = res[l][key];
  24. for (var i = 2; i < arguments.length; ++i) {
  25. s = s.replace('%' + (i - 1), '' + arguments[i]);
  26. }
  27. }
  28. return s;
  29. };
  30. // get selection string rect
  31. var getSelectionRect = function() {
  32. var rect = { left: 0, top: 0, right: 0, bottom: 0 };
  33. var selAll = document.getSelection();
  34. var selLen = String(selAll).length;
  35. if (selLen) {
  36. var rect_ = selAll.getRangeAt(selAll.rangeCount - 1).getBoundingClientRect();
  37. rect = { left: rect_.left, top: rect_.top,
  38. right: rect_.right, bottom: rect_.bottom,
  39. width: rect_.width, height: rect_.height };
  40. }
  41. rect.left += window.pageXOffset;
  42. rect.top += window.pageYOffset;
  43. rect.right += window.pageXOffset;
  44. rect.bottom+= window.pageYOffset;
  45. return selLen ? rect : null;
  46. };
  47.  
  48. // translation string resource
  49. var t = {
  50. en: {
  51. characters: '%1 characters',
  52. },
  53. ja: {
  54. characters: '%1 文字',
  55. },
  56. };
  57.  
  58. var timerId = null, elmInfo = null;
  59. // trigger for select change event
  60. document.addEventListener("selectionchange", function(e){
  61. if (elmInfo) {
  62. document.body.removeChild(elmInfo);
  63. elmInfo = null;
  64. }
  65. if (timerId)
  66. clearTimeout(timerId);
  67. // 250ms delay for display info
  68. timerId = setTimeout(function(){
  69. var rect = getSelectionRect();
  70. if (rect) {
  71. var selCount = String(document.getSelection()).length;
  72. elmInfo = document.createElement('div');
  73. elmInfo.style.cssText = [
  74. 'position: absolute',
  75. 'left: ' + (rect.right - 16) + 'px',
  76. 'top: ' + rect.bottom + 'px',
  77. 'background-color: #fff',
  78. 'border: 1px solid #666',
  79. 'border-radius: 5px',
  80. 'white-space: nowrap',
  81. 'padding: 0 3px'
  82. ].join(';');
  83. elmInfo.appendChild(document.createTextNode(_(t, 'characters', selCount)));
  84. document.body.appendChild(elmInfo);
  85. }
  86. }, 250);
  87. }, false);
  88. })();