如何从所选文本中获取邻居角色?

编程入门 行业动态 更新时间:2024-10-26 04:26:30
本文介绍了如何从所选文本中获取邻居角色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个这样的字符串:

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>

更多推荐

如何从所选文本中获取邻居角色?

本文发布于:2023-11-25 08:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629123.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:所选   邻居   角色   文本中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!