gpt4 book ai didi

javascript - 如何从文本区域中突出显示的文本中获取相邻字符?

转载 作者:行者123 更新时间:2023-11-28 06:29:19 25 4
gpt4 key购买 nike

这将返回突出显示的文本:

function getSelection(elem) {
var selectedText;

if (document.selection != undefined) { // IE
elem.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
} else if (elem.selectionStart != undefined) { // Firefox
var startPos = elem.selectionStart;
var endPos = elem.selectionEnd;
selectedText = elem.value.substring(startPos, endPos)
}
return selectedText;
}

$(document).on('mousedown', 'button', function(e) {
var selection = getSelection( $('#txtarea').get(0) );
alert(selection);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txtarea">this is a test</textarea>
<button>highlighted text</button>

现在我需要从选定/突出显示的文本中选择相邻的字符。例如,如果选择 his is a t,那么我需要同时获取 t(L) 和 e (R) 字符。我怎样才能做到这一点?

最佳答案

试试这个

function GetSelection() {
var selection = "";

var textarea = document.getElementById("myArea");
if ('selectionStart' in textarea) {
// check whether some text is selected in the textarea
if (textarea.selectionStart != textarea.selectionEnd) {
selection = textarea.value.substring(textarea.selectionStart - 1, textarea.selectionEnd + 1);
}
} else { // Internet Explorer before version 9
// create a range from the current selection
var textRange = document.selection.createRange();
// check whether the selection is within the textarea
var rangeParent = textRange.parentElement();
if (rangeParent === textarea) {
selection = textRange.text;

}
}

if (selection == "") {
alert("No text is selected.");
} else {
alert("The current selection is: " + selection);
}
}
<body>
<textarea id="myArea" spellcheck="false">Select some text within this field.</textarea>
<button onclick="GetSelection ()">Get the current selection</button>
</body>

关于javascript - 如何从文本区域中突出显示的文本中获取相邻字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34847151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com