简体   繁体   English

从div获取突出显示的文本并复制到textarea javascript中

[英]Get highlighted text from div and copy into textarea javascript

Managed to get highlighted text from within a textarea and transfer it into another textarea. 设法从一个文本区域中获取突出显示的文本并将其传输到另一个文本区域中。 But when the code is edited so that it gets the highlighted text from within a div instead, it does not work... 但是,当对代码进行编辑以使其从div中获取突出显示的文本时,它将无法工作...

Any ideas why this is happening? 任何想法为什么会这样? Thanks. 谢谢。

<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>

fiddle: 小提琴:

https://jsfiddle.net/Lzgyh2kd/ https://jsfiddle.net/Lzgyh2kd/

I answered your question in the comments and deleted it. 我在评论中回答了您的问题并将其删除。

You're using selectionStart and selectionEnd methods that works only on input elements. 您正在使用仅适用于输入元素的selectionStartselectionEnd方法。 For your solution used instead document.selection.createRange().text that gets the selected text in the document (inputs, divs, etc., doesn't matter). 对于您的解决方案,使用document.selection.createRange().text来获取文档中的选定文本(输入,div等)都没有关系。

Here's the fiddle: 这是小提琴:

Working demo 工作演示

Someone in the comments answered it with a fiddle that had two textarea, but edited one to a div and it seems to work. 评论中的某人用带有两个textarea的小提琴回答了该问题,但将其中一个编辑为div,它似乎起作用。 Cheers. 干杯。 (Edit- turns out a div was not required, it took straight from the page, so a workaround) (编辑-不需要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>

Working fiddle here: 在这里工作的小提琴:

https://jsfiddle.net/eLwy4eLp/1/ https://jsfiddle.net/eLwy4eLp/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM