javascript - vscode : how to get position of cursor in the document?

标签 javascript html visual-studio-code

我正在开发一个 vscode 扩展。我想获取整个文档的光标位置引用,例如,如果我有以下 html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<|body>
  <div>
    <p>Hello World</p>
  </div>
</body>
</html>

并且 cursur 在 body 标记内(上面代码中 | 符号的位置),我想要的结果是 178,如果你开始计算所有字符,它是字符的索引在文档中(包括空格)从头开始。

我试过这段代码

    const position = editor.selection.active;
    console.log(position);

但它给出了行和字符在该行中的位置,这不是我需要的。

有什么办法可以得到想要的输出吗?

最佳答案

使用下面的调用

editor.document.offsetAt(editor.selection.active)

Selection 有 4 个 Position 属性:

  • start, end : 相对于文件开头的位置
  • anchor, active : 光标开始和停止的位置进行选择

关于javascript - vscode : how to get position of cursor in the document?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65261663/

相关文章:

javascript - 在 JavaScript 中正确格式化 JavaScript

javascript - 如何使用 document.getElementsByClassName ("Class_Name"直接更改 JS 中的样式属性)

javascript - 是否有纯 Javascript X/HTML 验证器?

visual-studio-code - 如何使用带有 yaml 扩展名的文件在 vscode 中预览 asciidoc

regex - VSCode 通配符搜索和替换正则表达式

javascript - 理解 Dart 的元素事件

javascript - 在 javascript 和 HTML 中从 ResourceBundle 中获取字符串

javascript - 视频 - 拍摄快照

javascript - 渐进式网页应用。 Service Worker 通知出现多次

visual-studio-code - vscode : How to set that when I press CTRL + up or down arrow, 光标随页面移动?