在满足要素中的标记式自动完成和插入/光标移动

时间:2010-05-09 15:34:59

标签: javascript contenteditable caret

我正在研究一个jQuery插件,它允许你做@username样式标签,就像Facebook在状态更新输入框中那样。

我的问题是,即使经过数小时的研究和试验,简单地移动插入符号似乎也很难。我已经设法用某个人的名字注入了<a>标签,但是把它放在它之后似乎是火箭科学,特别是如果它在所有浏览器中都可以使用的话。

我还没有考虑用标签替换已键入的@username文本,而不是仅仅按照我正在做的那样注入它... lol

有很多关于在Stack Overflow上使用contenteditable的问题,我想我已经阅读了所有这些,但它们并没有真正涵盖我需要的内容。所以任何人都可以提供的更多信息都会很棒:)

3 个答案:

答案 0 :(得分:5)

您可以使用my Rangy library,它会尝试标准化浏览器范围和选择实施。如果您已设法插入<a>,并且已在名为aElement的变量中插入,则可以执行以下操作:

var range = rangy.createRange();
range.setStartAfter(aElement);
range.collapse(true);
var sel = rangy.getSelection();
sel.removeAllRanges();
sel.addRange(range);

答案 1 :(得分:3)

我对此感兴趣,所以我写了一个完整解决方案的起点。以下内容使用我的Rangy library及其selection save/restore module来保存和恢复选择并规范化跨浏览器问题。它用链接元素包围所有匹配的文本(在这种情况下为@whatever),并将选择放在之前的位置。这是在一秒钟没有键盘活动后触发的。它应该是可以重复使用的。

function createLink(matchedTextNode) {
    var el = document.createElement("a");
    el.style.backgroundColor = "yellow";
    el.style.padding = "2px";
    el.contentEditable = false;
    var matchedName = matchedTextNode.data.slice(1); // Remove the leading @
    el.href = "http://www.example.com/?name=" + matchedName;
    matchedTextNode.data = matchedName;
    el.appendChild(matchedTextNode);
    return el;
}

function shouldLinkifyContents(el) {
    return el.tagName != "A";
}

function surroundInElement(el, regex, surrounderCreateFunc, shouldSurroundFunc) {
    var child = el.lastChild;
    while (child) {
        if (child.nodeType == 1 && shouldSurroundFunc(el)) {
            surroundInElement(child, regex, surrounderCreateFunc, shouldSurroundFunc);
        } else if (child.nodeType == 3) {
            surroundMatchingText(child, regex, surrounderCreateFunc);
        }
        child = child.previousSibling;
    }
}

function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
    var parent = textNode.parentNode;
    var result, surroundingNode, matchedTextNode, matchLength, matchedText;
    while ( textNode && (result = regex.exec(textNode.data)) ) {
        matchedTextNode = textNode.splitText(result.index);
        matchedText = result[0];
        matchLength = matchedText.length;
        textNode = (matchedTextNode.length > matchLength) ?
            matchedTextNode.splitText(matchLength) : null;
        surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
        parent.insertBefore(surroundingNode, matchedTextNode);
        parent.removeChild(matchedTextNode);
    }
}

function updateLinks() {
    var el = document.getElementById("editable");
    var savedSelection = rangy.saveSelection();
    surroundInElement(el, /@\w+/, createLink, shouldLinkifyContents);
    rangy.restoreSelection(savedSelection);
}

var keyTimer = null, keyDelay = 1000;

function keyUpLinkifyHandler() {
    if (keyTimer) {
        window.clearTimeout(keyTimer);
    }
    keyTimer = window.setTimeout(function() {
        updateLinks();
        keyTimer = null;
    }, keyDelay);
}

HTML:

<p contenteditable="true" id="editable" onkeyup="keyUpLinkifyHandler()">
    Some editable content for @someone or other
</p>

答案 2 :(得分:1)

如你所说,你已经可以在插入符号处插入标记,我将从那里开始。首先要做的是在插入标签时为其添加标签。你应该有这样的东西:

<div contenteditable='true' id='status'>I went shopping with <a href='#' id='atagid'>Jane</a></div>

这是一个将光标放在标记之后的函数。

function setCursorAfterA()
{
    var atag = document.getElementById("atagid");
    var parentdiv = document.getElementById("status");
    var range,selection;
    if(window.getSelection) //FF,Chrome,Opera,Safari,IE9+
    {
        parentdiv.appendChild(document.createTextNode(""));//FF wont allow cursor to be placed directly between <a> tag and the end of the div, so a space is added at the end (this can be trimmed later)
        range = document.createRange();//create range object (like an invisible selection)
        range.setEndAfter(atag);//set end of range selection to just after the <a> tag
        range.setStartAfter(atag);//set start of range selection to just after the <a> tag
        selection = window.getSelection();//get selection object (list of current selections/ranges)
        selection.removeAllRanges();//remove any current selections (FF can have more than one)
        parentdiv.focus();//Focuses contenteditable div (necessary for opera)
        selection.addRange(range);//add our range object to the selection list (make our range visible)
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createRange();//create a "Text Range" object (like an invisible selection)
        range.moveToElementText(atag);//select the contents of the a tag (i.e. "Jane")
        range.collapse(false);//collapse selection to end of range (between "e" and "</a>").
        while(range.parentElement() == atag)//while ranges cursor is still inside <a> tag
        {
             range.move("character",1);//move cursor 1 character to the right
        }
        range.move("character",-1);//move cursor 1 character to the left
        range.select()//move the actual cursor to the position of the ranges cursor
    }
    /*OPTIONAL: 
    atag.id = ""; //remove id from a tag
    */
}

修改 经过测试和修复的脚本。它肯定适用于IE6,chrome 8,firefox 4和opera 11.没有其他浏览器可以测试,但它不使用最近更改过的任何函数,所以它应该适用于支持contenteditable的任何东西。 / p>

此按钮便于测试: <input type='button' onclick='setCursorAfterA()' value='Place Cursor After &lt;a/&gt; tag' >

尼科