IE9 javascript:等到选择结束

时间:2012-03-20 15:39:36

标签: javascript javascript-events internet-explorer-9

我有这个捕获所选文本的脚本,我想只在选择文本结束时做一些事情,而不是在选择是在progess时,浏览器只是IE9 文本也可以通过doubleclikking一个单词来选择,在这种情况下函数也应该做一次,当我使用onMouseUp这是两次

<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>

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

IE支持selectionchange对象上的Document事件,它比select事件更有用,但仍然无法完全按照您的要求执行,因为双击的过程可能会发生变化选择不止一次,因此发生多次selectionchange事件。

以下是使用该事件的示例,该事件至少可以在IE 6中使用IE:

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();
    }
};