如何防止在进行选择时清除文本框

how to prevent unclearing a textbox when selection is made?

本文关键字:清除 文本 选择 行选 何防止      更新时间:2024-06-09

我正在尝试构建一个文本编辑器,为此我使用文本区域来填充我的文本

我的问题是,当我点击一个按钮时,文本区域的选择就消失了。

以下是一些显示问题的代码:

    <!DOCTYPE html>
    <html>
    <body>
    
    Address:<br>
    <textarea id="myTextarea">
    California Road
    </textarea>
    
    <p>Click the button to select the contents of the text area.</p>
    
    <button type="button">Try it</button>
    
    </body>
    </html>

选择不会丢失,只是在文本区域未聚焦时不会显示。在Firefox、Chrome或IE10上尝试以下代码:http://jsfiddle.net/swwqd700/

HTML部分:

Address:<br>
<textarea id="myTextarea">
California Road
</textarea>    
<p>Click the button to select the contents of the text area.</p>
<button id="button">Try it</button>

Javascript部分:

function go() {
    var e = document.getElementById("myTextarea");
    var startPos = e.selectionStart;
    var endPos = e.selectionEnd;
    var selection = e.value.substring(startPos, endPos)    ;
    alert("It seems to have disappeared, but...'n'"" + selection + "'"");
    e.focus();
}
var btn = document.getElementById("button");
btn.addEventListener(
    "click",
    go,
    false
);

如果你想添加bbcode功能,你可能想看看这个线程:

jQuery设置文本区域中的光标位置

此外,这段代码(取自Tim Down在本线程中的Get the Highlighted/Selected text)可能会有所帮助:

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}