2015-09-29 25 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>