是否可以在 DIV 中选择一些文本并在选择后立即(即在释放鼠标按钮后立即)一个 SPAN 出现在所选文本旁边。我不喜欢使用 jQuery - 如果可能,只使用 Javascript + CSS。
附言。理想情况下,应该可以在同一个 DIV 中选择多次,并且跨度应该只出现在最新的选择中(并从之前的选择中消失)。
选择前
<div>Some text to select</div>
选择后
<div>Some text to select <span>[selected!]</span></div>
最佳答案
使用已回答问题中的代码 HERE ,我设法为您找到了解决方案。
HTML:
一些测试文本供您选择Javascript:
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
function doSomethingWithSelectedText() {
var selectedText = getSelectedText();
if (selectedText) {
document.getElementById('selectedSpan').innerHTML = selectedText;
}
}
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
关于javascript - 选择一些文本后,应该会出现一个新的跨度(仅限 Javascript + CSS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23598455/