[英]Get highlighted text from div and copy into textarea javascript
設法從一個文本區域中獲取突出顯示的文本並將其傳輸到另一個文本區域中。 但是,當對代碼進行編輯以使其從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>
小提琴:
我在評論中回答了您的問題並將其刪除。
您正在使用僅適用於輸入元素的selectionStart
和selectionEnd
方法。 對於您的解決方案,使用document.selection.createRange().text
來獲取文檔中的選定文本(輸入,div等)都沒有關系。
這是小提琴:
評論中的某人用帶有兩個textarea的小提琴回答了該問題,但將其中一個編輯為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>
在這里工作的小提琴:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.