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

时间:2015-02-26 12:20:37

标签: javascript onclick textarea selection

我正在尝试建立一个texteditor,为此我使用textarea来填写我的文本

我的问题是当我点击一个按钮时,textarea选择消失了。

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



    <!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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

如果您想添加bbcode功能,可能需要查看此主题:

jQuery Set Cursor Position in Text Area

此代码(摘自此帖子Get the Highlighted/Selected text中的Tim Down)可能有所帮助:

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

答案 1 :(得分:0)

选择不会丢失,但只有在textarea未聚焦时才会显示。 在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
);