如何从所选文本中获取邻居角色? [英] How to get neighbor character from selected text?

查看:64
本文介绍了如何从所选文本中获取邻居角色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串:

I have a string like this:

var comment = 'this is a test';

假设此i 已被选中,现在我需要 null (左侧)和 s (右侧)。我怎样才能得到它们?

Assume this i is selected, Now I need to null (left side) and s (right side). How can I get them?

我可以选择这样的文字:

I can get selected text like this:

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}

var selected_text = getSelectionHtml();


推荐答案

document.addEventListener("click", function() {
  var selection = window.getSelection();
  // Check if there are any ranges selected.
  if (selection.rangeCount > 0 && selection.type == "Range") {
    // Text content of the element.
    var text = selection.anchorNode.textContent;
    // selection.anchorOffset is the start position of the selection
    var before = text.substring(selection.anchorOffset-1, selection.anchorOffset);
    // selection.extentOffset is the end position of the selection
    var after = text.substring(selection.extentOffset, selection.extentOffset+1);
    // Check if there are any letters before or after selected string.
    // If not, change before and after to null.
    before = before.length === 1 ? before : null;
    after = after.length === 1 ? after : null;
    console.log(before, after);
  }
});

<div>this is a test</div>

要获得两个字符:

document.addEventListener("click", function() {
  var selection = window.getSelection();
  // Check if there are any ranges selected.
  if (selection.rangeCount > 0 && selection.type == "Range") {
    // Text content of the element.
    var text = selection.anchorNode.textContent;
    // selection.anchorOffset is the start position of the selection
    var before = text.substring(selection.anchorOffset-2, selection.anchorOffset);
    // selection.extentOffset is the end position of the selection
    var after = text.substring(selection.extentOffset, selection.extentOffset+2);
    // Check if there are any letters before or after selected string.
    // If not, change before and after to null.
    before = before.length >= 1 ? before : null;
    after = after.length >= 1 ? after : null;
    console.log(before, after);
  }
});

<div>this is a test</div>

这篇关于如何从所选文本中获取邻居角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆