在javascript中的Mozilla firefox问题

时间:2011-02-08 09:09:22

标签: javascript

我如何获得(如果)在文本框中选择任何文本,我想在任何javascript变量中获取它....特别是对于Mozilla firefox ...?提前谢谢!

3 个答案:

答案 0 :(得分:1)

这应该有效:

 alert(document.getElementById('TextBoxID').value);

将该值赋予某个变量:

 var variablename = document.getElementById('TextBoxID').value

编辑:我刚看到您只想阅读所选文字。这可以这样做:

 if (TextBox.selectionStart != undefined)
  {
    var startPos = TextBox.selectionStart;
    var endPos = TextBox.selectionEnd;
    var selectedText = TextBox.value.substring(startPos, endPos)
   }
  alert("You selected: " + selectedText);
}

如果您只需要知道用户是否选择了任何内容,您就可以:

var hasSelected = (TextBox.selectionStart != undefined)

答案 1 :(得分:0)

答案 2 :(得分:0)

<script type="text/javascript">
function getSelText() {
    var txt = '';
     if (window.getSelection) {
        txt = window.getSelection();
     } else if (document.getSelection)  {
        txt = document.getSelection();
    }
    else if (document.selection) {
        txt = document.selection.createRange().text;
    } else {
            return;
        }
        document.aform.selectedtext.value =  txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()" />