我有一个像这样的字符串:
var comment = 'this is a test';
Assume this i
已选择,现在我需要null
(左侧)和s
(右边)。我怎样才能得到它们?
我可以像这样获取选定的文本:
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)