你能用Javascript获得字符串中单击的确切位置吗?

时间:2012-06-07 00:21:23

标签: javascript html click mootools

我有这个html:<span>some words here</span>。单击span后,它将变为带有该字符串的文本框。有没有办法找出点击发生在哪个字符,并在带有字符串的文本框出现后将光标放在字符串中的那个点?

1 个答案:

答案 0 :(得分:1)

这是一个快速的小提琴(在Chrome中测试),适用于包含换行符的<span>,上面的解决方案会阻塞它:

http://jsfiddle.net/x2dLW/1/

总结如下:

function swapArea(baseEl) {
  // Display <textarea> element, hide the <span>
}

function getCursorLoc (nodes, range) {
  var prevChars = 0;
  var clickContent = range.startContainer.textContent;
  var clickLine;

  //iterate backwards through nodes constituting <span> element contents
  for (x = nodes.length - 1; x >= 0; x--) {
    node = nodes[x];

    if (clickContent == node.textContent) {
      clickLine = node; //this is the line user clicked in
    }
    else if (clickLine && (node.nodeName == "#text") ) {
      //sum up length of text lines prior, +1 for the NewLine
      prevChars += node.textContent.length + 1;
    }
  }

  //return offset in line clicked + sum length of all previous lines' content
  return range.startOffset + prevChars;
}

function replaceAndSet(e) {
    //Capture the click target as Selection(), convert to Range();
    var userRange = window.getSelection().getRangeAt();

    newArea = swapArea(source);

    //spanLines holds siblings (nodeName #Text or <BR>) constituting <span> contents
    var spanLines = userRange.startContainer.parentElement.childNodes;
    var clickChar = getCursorLoc(spanLines, userRange);

    newArea.focus();
    newArea.setSelectionRange(clickChar, clickChar);    
}

var source = someSpan; //the span user clicks on
source.onclick = replaceAndSet;