2015-09-29 29 views

回答

2

试试这个--------------------

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset=utf-8 /> 
    <title>JS Bin</title> 
    <script> 

     function SelectText() { 
      var input = document.getElementById("mytextbox"); 
      input.focus(); 
      input.setSelectionRange(2, 5); 

      var selObj = Window.toString(); 
      //window.getselection returs the object of current selection 
      alert(selObj); 

     } 
    </script> 
</head> 
<body> 
    <p><input type="text" id="mytextbox" size="20" value="getselection" /></p> 
    <p><button onclick="SelectText()">Select text</button></p> 
</body> 
</html> 
+0

如何为浏览器支持反正?我听到ie11删除“选择” – Asperger

+0

浏览器支持IE 9不超过 –

1

那些没有信息是不一样的事情:getSelection返回页面上的当前选择作为一个对象,它是的Selection一个实例。由于getSelection返回的对象是Selection的实例,因此它将继承其所有方法和属性(包括toString,修改等等)。因此,要解决您的问题,您必须getSelection才能获取,设置和修改页面上的选择。

有些文档here on MDN

0
Try this .. you may get an idea about version support and getselection 

<head> 
    <script type="text/javascript"> 
     function GetSelectedText() { 
      var selText = ""; 
      if (window.getSelection) { 
       // Supports all browsers, except IE before version 9 
       if (document.activeElement && 
         (document.activeElement.tagName.toLowerCase() == "textarea" || 
         document.activeElement.tagName.toLowerCase() == "input")) { 
        var text = document.activeElement.value; 
        selText = text.substring(document.activeElement.selectionStart, 
               document.activeElement.selectionEnd); 
       } 
       else { 
        var selRange = window.getSelection(); 
        selText = selRange.toString(); 
       } 
      } 
      else { 
       if (document.selection.createRange) { 
// for Internet Explorer 
        var range = document.selection.createRange(); 
        selText = range.text; 
       } 
      } 
      if (selText !== "") { 
       alert(selText); 
      } 
     } 
    </script> 
</head> 
<body onmouseup="GetSelectedText()"> 
    Some text for selection. 
    <br /><br /> 
    <textarea>Some text in a textarea element.</textarea> 
    <input type="text" value="Some text in an input field." size="40" /> 
    <br /><br /> 
    Select some content on this page! 
</body>