10

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

我的问题是,即使经过数小时的研究和实验,简单地移动插入符号似乎真的很困难。我已经设法在<a>标签中注入了某人的名字,但是将插入符号放在它之后看起来像是火箭科学,特别是如果它应该在所有浏览器中都可以工作。

而且我什至还没有考虑用@username标签替换键入的文本,而不仅仅是像我现在所做的那样注入它......哈哈

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

4

3 回答 3

5

您可以使用我的 Rangy 库,它尝试对浏览器范围和选择实现进行规范化并取得了一些成功。如果您设法<a>按照您的说法插入 并且将其放入名为 的变量中aElement,则可以执行以下操作:

var range = rangy.createRange();
range.setStartAfter(aElement);
range.collapse(true);
var sel = rangy.getSelection();
sel.removeAllRanges();
sel.addRange(range);
于 2010-10-20T21:54:38.607 回答
3

我对此很感兴趣,所以我写了一个完整解决方案的起点。以下使用我的Rangy 库及其选择保存/恢复模块来保存和恢复选择并规范跨浏览器问题。它用一个链接元素包围所有匹配的文本(在这种情况下为@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>
于 2010-10-26T18:19:16.403 回答
1

正如您所说,您已经可以在插入符号处插入标签,我将从那里开始。要做的第一件事是在插入标签时给它一个 id。然后你应该有这样的东西:

<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 的东西。

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

尼科

于 2010-10-19T20:42:57.593 回答