【问题标题】:how to prevent unclearing a textbox when selection is made?选择时如何防止清除文本框?
【发布时间】:2015-02-26 12:20:37
【问题描述】:

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

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

这里有一些代码来说明问题:

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

【问题讨论】:

  • @mplungjan — 它会带来什么好处?
  • 因为是表格,不能为空
  • 当我知道所选文本时,我可以添加一些标签@Quentin
  • 我也试过 input type = button @mplungjan

标签: javascript onclick textarea selection


【解决方案1】:

选择不会丢失,只是在 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
);

【讨论】:

    【解决方案2】:

    如果你想添加 bbcode 功能,你可能想看看这个帖子:

    jQuery Set Cursor Position in Text Area

    此代码(取自 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      相关资源
      最近更新 更多