在DOM #id上设置活动插入符号(在指定的div之前)

时间:2015-04-12 11:03:13

标签: javascript jquery cursor contenteditable caret

我需要在contenteditable div中使用#id设置DOM元素之后的插入位置。通过这种方式,我将能够继续输入文字。

一般问题是

  1. 获取指定DOM元素的插入位置(即带有#id的span或div)
  2. 将插入符号设置在此位置(即在此DOM元素之后+能够写入焦点的文本)

  3. 示例html结构:

    <div id="container" contenteditable="true">
        dasidjsaid<div id="el1">sdsad</div>fdfhsdhdsf<div id="el2">sdsad</div>afasf
        <div id="el3">test</div><div id="el4">jsj</div> <div id="el5">32</div>sadsa
    </div>
    

1 个答案:

答案 0 :(得分:0)

尝试一下:

&#13;
&#13;
function setToStart(element) {
  if(!element) {
    return;
  }
  
  element.focus();
  
  var range = document.createRange();
  range.setStart(element, 0);
  range.setEnd(element, 0);
  range.collapse(true);

  var sel = window.getSelection();
  sel.removeAllRanges();

  try {
    sel.addRange(range);
  } catch (e) { }
}

function setToEnd(element) {
  
    element.focus();

    var nodeStack = [element];
    var node = null;
    var lastNode = element;
    var charIndex = 0;

    while ((node = nodeStack.pop())) {
        if (node.nodeType === 3) {
            lastNode = node;
            charIndex = node.length;
        } else {
            var i = node.childNodes.length;
            while (i--) {
                nodeStack.push(node.childNodes[i]);
            }
        }
    }

    var range = document.createRange();
    range.setStart(lastNode, charIndex);
    range.setEnd(lastNode, charIndex);
    range.collapse(true);

    var sel = window.getSelection();
    sel.removeAllRanges();

    try {
        sel.addRange(range);
    } catch (e) { }
}


document.getElementById('setStart').addEventListener('click', function() {
  setToStart(document.getElementById('first'));
});
document.getElementById('setEnd').addEventListener('click', function() {
  setToEnd(document.getElementById('first'));
});
&#13;
<div contenteditable="true"><h1>Title</h1><p id="first">Vestibulum id ligula porta felis euismod semper. Curabitur blandit tempus porttitor. Cras justo odio, dapibus ac facilisis in, egestas eget quam.</p><p id="second">Nulla vitae elit libero, a pharetra augue. Aenean lacinia bibendum nulla sed consectetur.</p></div>

<button id="setStart">Set to START of first paragraph</button>
<button id="setEnd">Set to END of first paragraph</button>
&#13;
&#13;
&#13;