繁体   English   中英

在IE中单击跨度时,从textarea检索选定的文本

[英]Retrieving selected text from textarea when span is clicked in IE

单击“跨度”时,我想在文本区域中获取选定的文本。 当我单击按钮时,选择有效,但在单击跨度时不起作用。
也许是因为单击跨度时选择丢失了,但是单击按钮时却没有发生? 如何解决?

function Copy() {
  var theSelection = document.selection.createRange();
  alert(theSelection.text);           
}

 <div>
    <span class="Icon" onclick="Copy();"></span> <input type="button" value="Copy" onclick="Copy();" style="float:left;" />  
 </div>
 <div style="clear:both;">
    <textarea rows="2" cols="20" style="height:370px;width:800px;"></textarea> 
 </div>

仅限IE!

在线示例

更新:

这就是我在Firefox中做的事情:

if (window.getSelection){ // Firefox, Opera, Safari

   var textbox = document.getElementById("box");
   textbox.focus();
   theSelection = document.activeElement.value.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd);

alert(theSelection);
}

是的,就是这样:在点击事件触发时,选择已丢失。 如果您使用onmousedown而不是onclick ,它将起作用。

更新

仅在IE中有效的另一种方法是将以下属性添加到<span> 这将使跨度变为不可选择,从而防止跨度影响选择:

unselectable="on"

更新2

在其他浏览器中,获取所选文本的方法是使用selectionStartselectionEnd属性:

function Copy() {
    var textbox = document.getElementById("box");
    textbox.focus();
    var selectedText = "";
    if (typeof textbox.selectionStart == "number") {
        selectedText = textbox.value.slice(textbox.selectionStart, textbox.selectionEnd);
    } else if (document.selection) {
        selectedText = document.selection.createRange().text;
    }
    alert(selectedText);
}

暂无
暂无

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

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