这将返回突出显示的文本:
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句