设法从文本中心内获取突出显示的文本,并将其转移到另一个文本方面。但是,当编辑代码以使其从DIV内获取突出显示的文本时,它不起作用...
有什么想法为什么会发生这种情况?谢谢。
<div id="quote"> load transcript in here instead and grab text from here</div> // does not work
<textarea id="quote" readonly> // works
load transcript in here
</textarea>
<textarea contenteditable="false" id="output" name="selected"></textarea> // outputs highlighted text here
<script>
var quotearea = document.getElementById('quote')
var output = document.getElementById('output')
quotearea.addEventListener('mouseup', function(){
if (this.selectionStart != this.selectionEnd){ // check the user has selected some text inside field
var selectedtext = this.value.substring(this.selectionStart, this.selectionEnd)
output.innerHTML = selectedtext
}
}, false)
</script>
小提琴:
https://jsfiddle.net/lzgyh2kd/
我在评论中回答了您的问题并删除了。
您使用的是仅在输入元素上起作用的selectionStart
和selectionEnd
方法。对于您所使用的解决方案而不是在文档中获取所选文本的document.selection.createRange().text
(输入,divs等,都没关系)。
这是小提琴:
工作演示
评论中的某人用一个带有两个文本的小提琴回答了它,但将一个编辑为Div,似乎很有效。干杯。(编辑 - 事实证明不需要一个DIV,它直接从页面上完成,因此可以解决)
)<div name="" id="original">
Load transcript in here.
</div>
<textarea name="" id="copied" cols="30" rows="10"></textarea>
<script>
var text = '';
function copyText(e) {
text = (document.all) ? document.selection.createRange().text : document.getSelection();
document.getElementById('copied').value = text;
}
document.onmouseup = copyText;
if (!document.all) {
document.captureEvents(Event.MOUSEUP);
}
</script>
在这里工作小提琴:
https://jsfiddle.net/elwy4elp/1/