[关闭]
@dooy 2023-03-11T13:23:44.000000Z 字数 1101 阅读 105

JS知识储备

JS


GrammarLy 谷歌插件前端坐标核心解析

我们都知道GrammarLy 能准确定位 错误的位置,后端是通过文本的offset 来定位的,那么对应前端怎么来定位呢?

我们都知道获取某个node的定位但是不知道 如何活得文本的定位,昨天自己研究一天并在stackoverflow 发问,后面有人已经实现了这个代码,使用Range 中的 getClientRects 活得坐标

  1. var range = document.createRange();
  2. range.setStart(parentElt, start);
  3. range.setEnd(parentElt, end);
  4. // These rects contain the client coordinates in top, left
  5. var rects = range.getClientRects();

但是有一个很大的问题 getClientRects 只支持 div p san 这样的targetName 对于textarea input 支持 range.setStart range.setEnd 就是不支持 getClientRects 返回的坐标都是0 0,后面再研究了GrammarLy 他同样也有这样的问题,但是他的实现是通过div 来做一个 镜像,把div的css style 特别是font 设置得跟textarea 一模一样然后通过 div 来获取坐标。 grammarly-mirror就是用来做这个工作的

另外一个收获是发现了 shadowRoot shadow-root 对应插件非常有用因为他不影响其他人css style

参考
Rank参考
HTMLTextAreaElement 参考

随机篇

获取对象坐标

  1. //取得对象坐标
  2. K.getCoords=function (node){
  3. var x = node.offsetLeft;
  4. var y = node.offsetTop;
  5. var parent = node.offsetParent;
  6. while (parent != null){
  7. x += parent.offsetLeft;
  8. y += parent.offsetTop;
  9. parent = parent.offsetParent;
  10. }
  11. return {x: x, y: y};
  12. }

正则表达式 换行

  1. let abc = "good sss=dd\n我们 eee";
  2. let regex = /sss=([\s\S]+?)\s+eee/; //匹配任何字符(包括换行符)
  3. let matches = abc.match(regex);
  4. if (matches) {
  5. console.log(matches[1]); // 输出 "dd\n我们"
  6. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注