2012-03-20 57 views
1

我有這個腳本捕捉選定的文本,我只想做一些事情時,選擇文本結束,而不是當選擇正在進行中,瀏覽器是IE9只有 文本也可以通過doubleclikking在這種情況下,功能也應該有所作爲一次,當我使用onMouseUp這個字被選中是IE9的javascript:等到選擇結束

<head> 
    <script type="text/javascript"> 
    function selectedText(){ 
     var doc = document.selection; 
     if(doc && doc.createRange().text.length != 0){ 
     log.innerHTML = doc.createRange().text; 
     } 
    } 
    </script> 
</head> 
<body onselect="selectedText();"> 
    <span id=sp>this is the text from where you can select one or more words</span> 
    <div id=log style="background-color=yellow;"></div> 
</body> 

回答

0

沒關係,想通了兩次,這是供將來參考

<head> 
    <script type="text/javascript"> 
     count = 0; 
     function selectedText(){ 
      var doc = document.selection; 
      if(doc && doc.createRange().text.length != 0){ 
      count++; 
      log.innerHTML = "count: "+count+" "+doc.createRange().text; 
      } 
     } 

     function AddEventHandler() { 
      var sp = document.getElementById ("sp"); 
      if (sp.addEventListener) { // all browsers except IE before version 9 
      sp.addEventListener ("click", selectedText, false); 
      } 
      else { 
      if (sp.attachEvent) { // IE before version 9 
       sp.attachEvent ('onmouseup', selectedText); 
      } 
      } 
     }; 
    </script> 
</head> 
<body onload=AddEventHandler()> 
    <span id=sp>this is the text from where you can select one or more words</span> 
    <div id=log style="background-color=yellow;"></div> 
</body> 

或更短的版本

<head> 
    <script type="text/javascript"> 
    count = 0; 
    document.onselectionchange = function() { 
     count++; 
     var sel = window.getSelection(); 
     if (sel.rangeCount > 0) { 
     var range = sel.getRangeAt(0); 
     document.getElementById("log") = count+":"+range.toString(); 
     } 
    }; 
    </script> 
</head> 
<body> 
    <span id=sp>this is the text from where you can select one or more words</span> 
    <div id=log style="background-color=yellow;"></div> 

</body> 
0

IE支持在Document對象比select事件的更多有用的,但仍然不會做完全按照你問一個selectionchange事件,因爲雙擊的過程中可能會改變選擇一次以上,因此火多於一個selectionchange事件。

下面是一個使用該事件,將在IE瀏覽器至少可以追溯到IE 6的例子:

document.onselectionchange = function() { 
    var sel = document.selection; 
    if (sel.type == "Text") { 
     var range = sel.createRange(); 
     document.getElementById("log") = range.text; 
    } 
}; 

如果你不關心早期版本的IE瀏覽器,你可以使用IE 9的支持標準DOM範圍和選擇的API,然後該代碼也將WebKit中工作:

document.onselectionchange = function() { 
    var sel = window.getSelection(); 
    if (sel.rangeCount > 0) { 
     var range = sel.getRangeAt(0); 
     document.getElementById("log") = range.toString(); 
    } 
}; 
+0

嘗試第二次在IE9但是當我拖動以選擇我只能選擇1或2個字符,則它停止 – peter 2012-03-22 16:28:21