在Internet Explorer8标准模式下,TextRange的offsetLeft和offsetTop属性失效。

9
我似乎发现了一个与Internet Explorer 8有关的问题,即查找Text Range的位置 - 例如当前选择的文本。我在StackOverflow或其他地方没有找到任何关于这个问题的报告。
TextRange.offsetLeft和TextRange.offsetTop报告范围的左上角,在所有我在IE8中看到的情况下,它们大致正确,除非范围在IFrame内。当范围在IFrame内时,offsetLeft和offsetTop的值会相对于IFrame在其父级内的位置向负方向偏移。(请参见下面的示例)
此问题仅出现在以下情况下:
  • 浏览器为IE8
  • 页面处于标准模式
此问题不会出现在以下情况下:
  • 浏览器为IE7或IE10
  • 页面处于怪异模式
我的问题:
  • 其他人能否确认这个问题或者我疯了?
  • 这是已知的问题吗?
  • 是否有任何明智的解决方案或工作区域?(明智的解决方案是指框架中的JS不需要知道其父窗口的任何信息)
谢谢。
问题示例:(请参见IE8与IE9之间的差异)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>IE8 IFrame Text Range Position Test Page</title>
        <style type="text/css">
            body {
                font-family: Tahoma;
            }
            #target {
                background-color: #CCC;
                position: absolute;
                left: 50px;
                top: 50px;
            }

            #bullsEye {
                position: absolute;
                background-color: red;
                width: 5px;
                height: 5px;
            }

            iframe {
                margin: 10px 75px;
            }
        </style>
        <script type="text/javascript" charset="utf-8">
            function target() {
                var range = document.body.createTextRange();
                range.moveToElementText(document.getElementById('target'));
                range.select();
                var bullsEye = document.createElement('div');
                bullsEye.id = 'bullsEye';
                bullsEye.style.left = range.offsetLeft + 'px';
                bullsEye.style.top = range.offsetTop + 'px';
                document.body.appendChild(bullsEye);
                document.getElementById('output').innerHTML = 'range.offsetLeft = ' + range.offsetLeft + ', range.offsetTop = ' + range.offsetTop;
            }
        </script>
    </head>
    <body>
        <div id="target">Target</div>
        <input type="button" value="Hit Target" onclick="target();"> <span id="output"></span>
        <br><br><br><br><br>
        <script>
            if (window.parent == window) document.write('<iframe src="?tfr" height="150" width="500"></iframe>');
        </script>
    </body>
</html>
3个回答

3
  • 我仍然认为这是IE8的一个错误,但有一个解决方法
  • 在标准模式下使用boundingLeftboundingRight。但在怪异模式下使用offsetLeftoffsetRight

3
我已经在我的IE 8(Windows XP上)中测试了您的示例页面,并且能够重现问题,所以我可以确认这个问题,但我不能确定它是否是已知问题。
我在这个答案中找到了一个可行的解决方案(至少在IE 8上;我无法确定它是否也适用于IE 7或IE 9,因为我没有这些版本的测试环境)。
这是我的修改后的测试页面:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>IE8 IFrame Text Range Position Test Page</title>
        <style type="text/css">
            body {
                font-family: Tahoma;
            }
            #target {
                background-color: #CCC;
                position: absolute;
                left: 50px;
                top: 50px;
            }

            #bullsEye {
                position: absolute;
                background-color: red;
                width: 5px;
                height: 5px;
            }

            iframe {
                margin: 10px 75px;
            }
        </style>
        <script type="text/javascript" charset="utf-8">
            function getSelectionTopLeft() {     
                var x = 0, y = 0;     // Use standards-based method only if Range has getBoundingClientRect     
                if (window.getSelection && document.createRange && 
                    typeof document.createRange().getBoundingClientRect != "undefined") {         
                    var sel = window.getSelection();         
                    if (sel.rangeCount > 0) {             
                        var rect = sel.getRangeAt(0).getBoundingClientRect();             
                        x = rect.left;             
                        y = rect.top;         
                    }     
                } else if (document.selection && document.selection.type != "Control") {         // All versions of IE         
                    var textRange = document.selection.createRange();         
                    x = textRange.boundingLeft;         
                    y = textRange.boundingTop;     
                }     
                return { x: x, y: y }; 
            }                   

            function target() {
                var range = document.body.createTextRange();
                range.moveToElementText(document.getElementById('target'));
                range.select();
                var bullsEye = document.createElement('div');
                bullsEye.id = 'bullsEye';
                bullsEye.style.left = range.offsetLeft + 'px';
                bullsEye.style.top = range.offsetTop + 'px';
                document.body.appendChild(bullsEye);
                //document.getElementById('output').innerHTML = 'range.offsetLeft = ' + range.offsetLeft + ', range.offsetTop = ' + range.offsetTop;
                var tl = getSelectionTopLeft();
                document.getElementById('output').innerHTML = tl.x + ',' + tl.y;
            }
        </script>
    </head>
    <body>
        <div id="target">Target</div>
        <input type="button" value="Hit Target" onclick="target();"> <span id="output"></span>
        <br><br><br><br><br>
        <script>
            if (window.parent == window) document.write('<iframe src="?tfr" height="150" width="500"></iframe>');
        </script>
    </body>
</html>

请也查看Rangy库

一款跨浏览器的JavaScript范围和选择库。它提供了一个简单的基于标准的API,用于在所有主要浏览器中执行常见的DOM范围和选择任务,将在Internet Explorer 8及以下版本与符合DOM标准的浏览器之间实现这种功能的巨大差异抽象出来。


我相信 getBoundingClientRect 返回的是相对于窗口的坐标,所以如果你的文档大小是窗口视口的两倍,那么选择的坐标将不正确。 - daedelus_j

3
在过去,为了在浏览器中获得一致的选择位置,我使用插入 span 元素并从该元素读取数据的方法... 这有点 hacky,但似乎更可靠。
通过这种方式,您应该完全避免特定的 bug... 我不知道这是否被视为明智的做法 ;) 不过它已经在所有这些用户代理上进行过测试并且工作正常:
  1. Mac OSX FF15/FF16
  2. Mac OSX Safari 5.1.7
  3. Mac OSX Chrome 22
  4. Mac OSX Opera 12
  5. Win XP FF 3.6
  6. Win XP Safari 3.1
  7. Win XP IE7/IE8
  8. Win 7 IE9
  9. Win 7 FF15
  10. Win 7 Chrome 22
(以下代码依赖于 jQuery,最好是 1.8+) jsfiddle: http://jsfiddle.net/vCWha/ css:
#__span__    {
  display: inline !important;
  *display: inline-block !important; /* IE7 works better with inline-block */
}

/* you can obviously ignore these, they are just used to show accuracy */
.crosshair-v {
  height: 0;
  width: 20px;
  border-bottom: 1px solid red;
  position: absolute;
  margin-left: -10px;
}

.crosshair-h {
  height: 20px;
  width: 0;
  border-right: 1px solid red;
  position: absolute;
  margin-top: -9px;
}

javascript

(function($){
  $(function(){
    var span = $('<span id="__span__" />').get(0),
        crv = $('<div class="crosshair-v" />'),
        crh = $('<div class="crosshair-h" />');
    $('body').append(crv).append(crh);
    var getSelectionTopLeft = function(){
      var s,e,a,p,o,r,t;
      try{
        /// IE9+, FF, Chrome, Safari, Opera
        if ( window.getSelection ){
          s = window.getSelection();
          r = s.getRangeAt(0);
          a = r.startContainer;
          p = a.parentNode;
          if ( a.nodeType == 3 ){
            t = a.splitText(r.startOffset);
            p.insertBefore(span, t);
          }
          else if ( a.nodeType == 1 ){
            p.insertBefore(span, a);
          }
          o = $(span).position();
        }
        /// IE8-
        else if ( (s = document.selection) && (s.type != 'Control') ) {
          r = s.createRange();
          r.move('character',0);
          $('#__span__').remove();
          r.pasteHTML(span.outerHTML);
          o = $('#__span__').position();
        }
        /// quick fallback for certain older browsers for 
        /// whom $().position() fails.
        if ( o && o.left === 0 && o.left === o.top ) {
          e = span;
          while( e.offsetParent ){
            o.left += e.offsetLeft;
            o.top += e.offsetTop;
            e = e.offsetParent;
          }
        }
      }catch(ex){}
      return o;
    }
    $(document).mouseup(function(e){
      /// execute our function to calculate the selection position
      var o = getSelectionTopLeft();
      if ( o ){
        /// update the crosshair
        crv.css(o);
        crh.css(o);
      }
    });
  });
})(typeof jQuery != 'undefined' && jQuery);

更新

昨晚我有更多时间来改进这个代码,以下是将我的改进代码应用到你的示例中 - 下面的代码应该在各种浏览器中都能正常运行(至少大致如此):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <title>IE8 IFrame Text Range Position Test Page</title>
  <style type="text/css">
    body {
        font-family: Tahoma;
    }

    #__span__    {
      display: inline !important;
      display: inline-block !important;
      min-height: 1em;
    }

    #target {
        background-color: #CCC;
        position: absolute;
        left: 50px;
        top: 50px;
    }

    #bullsEye {
        position: absolute;
        background-color: red;
        width: 5px;
        height: 5px;
    }

    iframe {
        margin: 10px 75px;
    }
  </style>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <script type="text/javascript" charset="utf-8">
    (function($){
        var bullsEye = $('<div id="bullsEye" />'), span = $('<span id="__span__"></span>').get(0);

        /// var is missed here on purpose to make the function globally accessible
        target = function() {                
          moveSelectionToElement( document.getElementById('target') );
          bullsEye
            .css( getSelectionTopLeft() )
            .appendTo('body');
        }

        /// because selectNodeContents seems to select outside the node we 
        /// need our own rangeToNodeContents that only highlights text nodes
        /// this is a side effect of having code inserted ranges & selections.
        var rangeToNodeContents = function(r, node){
          var i, l, tns = [];
          if ( node.nodeType == 1 && node.childNodes && (l = node.childNodes.length) ){
            for ( i=0;i<l;i++ ){
              if ( node.childNodes[i] && node.childNodes[i].nodeType == 3 ) {
                tns.push(node.childNodes[i]);
              }
              if ( tns.length > 1 ) {
                r.setStart(tns[0],0);
                r.setEnd(tns[tns.length-1],tns[tns.length-1].nodeValue.length);
              }
              else {
                r.selectNodeContents(node);
              }
            }
          }
          else {
            r.selectNodeContents(node);
          }
        }

        /// cross browser selection creator
        var moveSelectionToElement = function(elm) {
          var s,w,r,d; w = window; d = document;
          if (w.getSelection && d.createRange) {
            s = w.getSelection();
            r = d.createRange();
            rangeToNodeContents( r, elm );
            s.removeAllRanges();
            s.addRange(r);
          } else if (d.selection && d.body && d.body.createTextRange) {
            r = elm.createTextRange();
            r.select();
          }
        }

        /// cross browser getSelectionTopLeft
        var getSelectionTopLeft = function(){
          var s,e,a,p,o,r,t; o = {left:0,top:0};
          try{
            if ( window.getSelection ){
              s = window.getSelection();
              r = s.getRangeAt(0);
              a = r.startContainer;
              p = a.parentNode;
              if ( a.nodeType == 3 ){
                t = a.splitText(r.startOffset);
                p.insertBefore(span, t);
              }
              else if ( a.nodeType == 1 ){
                  p.insertBefore(span, a);
              }
              o = $(span).offset();
            }
            else if ( (s = document.selection) && (s.type != 'Control') ) {
              r = s.createRange();
              r.move('character',0);
              $('#__span__').remove();
              r.pasteHTML(span.outerHTML);
              o = $('#__span__').offset();
            }
            if ( o && o.left === 0 && o.left === o.top ) {
              e = span;
              while( e.offsetParent ){
                o.left += e.offsetLeft;
                o.top += e.offsetTop;
                e = e.offsetParent;
              }
            }
          }catch(ex){}
          return o;
        }

    })(typeof jQuery != 'undefined' && jQuery);
  </script>
</head>
<body>
  <div id="target">Target <b>abc</b> test</div>
  <input type="button" value="Hit Target" onmouseup="target();"> <span id="output"></span>
  <br><br><br><br><br>
  <script>
    if (window.parent == window){
      document.write('<iframe src="?tfr" height="150" width="500"></iframe>');
    }
  </script>
</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接