我有两个<textarea>,一个是id="input",另一个是id="selection"。
<textarea id="input">将包含一些超文本标记语言。用户将在该文本区域中选择一些文本,单击一个按钮,所选文本将被复制到<textarea id="selection">。
我可以使用jQuery或普通的JavaScript,我希望它能在IE7+,Safari和火狐中工作。
发布于 2010-12-03 11:56:00
只有一种方法我能做到。正如您可能知道的,您遇到的问题是,当您单击按钮(从而触发事件以复制选择)时,文本区域失去焦点,因此没有文本被选中。
因此,作为一种变通方法,我设置了一个div的样式,使其看起来(有点)像一个文本区域。这似乎是可行的:
<style type="text/css">
    .textarea { 
        border:1px solid black; 
        width:200px; 
        height:100px; 
        overflow-y: auto; 
        float:left; 
    }
</style>然后,标记如下所示:
<div id="input" class="textarea">This is a test</div>
<textarea id="selection"></textarea>
<button id="theButton">Copy</button>最后,脚本:
var selText = "";
$( document ).ready( function() {
    $( '#theButton' ).mousedown( function() {
        $( '#selection' ).val( getSelectedText() );
    });
});
function getSelectedText(){
    if ( window.getSelection ) {
        return window.getSelection().toString();
    }
    else if ( document.getSelection ) {
        return document.getSelection();
    } else if ( document.selection ) {
        return document.selection.createRange().text;
    }
} 为了充分证明这一点,我从http://esbueno.noahstokes.com/post/92274686/highlight-selected-text-with-jquery获得了getSelectedText()方法
https://stackoverflow.com/questions/4342229
复制相似问题