javascript-如何在IE中的contentEditable div中获取选定的textnode?

我正在尝试使用div标签上可编辑的HTML5创建一个简单的文本编辑器.如您所知,所选文本在IE中的处理方式大不相同.

    this.retrieveAnchorNode = function() {
      var anchorNode;
      if (document.selection)
        anchorNode = document.selection.createrange().parentElement();
      else if (document.getSelection)
        anchorNode = window.getSelection().anchorNode;
    }

我正在寻找一种获取所选textnode(而不是文本本身)的方法,就像我可以在其他浏览器上使用“ anchorNode”和“ focusNode”一样.我在IE上找到的唯一替代方法是“ parentElement()”函数,该函数仅设法选择contenteditable div本身.

有任何想法吗?

解决方法:

这是我从IERange开始需要的函数版本,并带有我的注释:

function getChildindex(node) {
  var i = 0;
  while( (node = node.prevIoUsSibling) ) {
    i++;
  }
  return i;
}

function getTextRangeBoundaryPosition(textRange, isstart) {
  var workingRange = textRange.duplicate();
  workingRange.collapse(isstart);
  var containerElement = workingRange.parentElement();
  var workingNode = document.createElement("span");
  var comparison, workingComparisonType = isstart ?
    "StartToStart" : "StartToEnd";

  var boundaryPosition, boundaryNode;

  // Move the working range through the container's children, starting at
  // the end and working backwards, until the working range reaches or goes
  // past the boundary we're interested in
  do {
    containerElement.insertBefore(workingNode, workingNode.prevIoUsSibling);
    workingRange.movetoElementText(workingNode);
  } while ( (comparison = workingRange.compareEndPoints(
    workingComparisonType, textRange)) > 0 && workingNode.prevIoUsSibling);

  // We've Now reached or gone past the boundary of the text range we're
  // interested in so have identified the node we want
  boundaryNode = workingNode.nextSibling;
  if (comparison == -1 && boundaryNode) {
    // This must be a data node (text, comment, cdata) since we've overshot.
    // The working range is collapsed at the start of the node containing
    // the text range's boundary, so we move the end of the working range
    // to the boundary point and measure the length of its text to get
    // the boundary's offset within the node
    workingRange.setEndPoint(isstart ? "EndToStart" : "EndToEnd", textRange);

    boundaryPosition = {
      node: boundaryNode,
      offset: workingRange.text.length
    };
  } else {
    // We've hit the boundary exactly, so this must be an element
    boundaryPosition = {
      node: containerElement,
      offset: getChildindex(workingNode)
    };
  }

  // Clean up
  workingNode.parentNode.removeChild(workingNode);

  return boundaryPosition;
}

var textRange = document.selection.createrange();
var selectionStart = getTextRangeBoundaryPosition(textRange, true);
// selectionStart has properties 'node' and 'offset'

相关文章

HTML5和CSS3实现3D展示商品信息的代码
利用HTML5中的Canvas绘制笑脸的代码
Html5剪切板功能的实现
如何通过HTML5触摸事件实现移动端简易进度条
Html5移动端获奖无缝滚动动画实现
关于HTML5和CSS3实现机器猫的代码