获取范围的开始以插入Div

时间:2012-03-19 00:43:19

标签: javascript css google-chrome-extension range

我正在尝试创建一个Google Chrome扩展程序,用户可以突出显示页面上的文字,并在文本的开头显示一张快乐的面孔。我找到了this网站,其中演示了如何存储和检索范围。我的问题是我如何获得范围的开头来插入我的< div id =“happyFace”>?

var selection = storeSelection(window.getSelection());
var selectionRange = restoreSelection(selection);
console.log( selectionRange.startContainer.offsetLeft ); //undefined


function makeXPath (node, currentPath) {
  /* this should suffice in HTML documents for selectable nodes, XML with namespaces needs more code */
  currentPath = currentPath || '';
  switch (node.nodeType) {
    case 3:
    case 4:
      return makeXPath(node.parentNode, 'text()[' + (document.evaluate('preceding-sibling::text()', node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']');
    case 1:
      return makeXPath(node.parentNode, node.nodeName + '[' + (document.evaluate('preceding-sibling::' + node.nodeName, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']' + (currentPath ? '/' + currentPath : ''));
    case 9:
      return '/' + currentPath;
    default:
      return '';
  }
}

function storeSelection (selectionObject) {
  if (typeof window.getSelection != 'undefined') {
    var selection = selectionObject;
    var range = selection.getRangeAt(0);
    if (range != null) {
       selectionObject = makeXPath(range.startContainer) + '|' + range.startOffset + '|' + makeXPath(range.endContainer) + '|' + range.endOffset;
       return selectionObject
    }
  }
}

function restoreSelection (selectionObject) {
  var selectionDetails = selectionObject;
  if (selectionDetails != null) {
    selectionDetails = selectionDetails.split(/\|/g);
    if (typeof window.getSelection != 'undefined') {
      var range = document.createRange();
      range.setStart(document.evaluate(selectionDetails[0], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[1]));
      range.setEnd(document.evaluate(selectionDetails[2], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[3]));
      return range;
    }
  }
}

1 个答案:

答案 0 :(得分:1)

非常简单,因为你只担心Chrome:

// Get the range
var range = document.getSelection().getRangeAt(0);
// Collapse it to the start
range.collapse(true);
// insert your node
range.insertNode(node);

以下是一个工作示例:http://jsfiddle.net/L5Qqk/。请注意,它一直在移动幸福的脸,因为我总是添加相同的节点。如果每次创建一个新节点,则会添加多个幸福面孔。