将光标设置在动态更改的contenteditable html标记的末尾

时间:2014-04-04 09:22:39

标签: jquery

在我的管理部分,我有一个“编辑”按钮

点击编辑时,内容应该是可编辑的

演示代码:

<ul>
    <li>
        <a onblur="noteditable(this);" >DisplayName</a>
        <span onclick="return editables(this);" >edit</span>
    </li>
    <li>
        <a onblur="noteditable(this);" >DisplayName</a>
        <span onclick="return editables(this);" >edit</span>
    </li>
</ul>

JS:

editables = function (Tabs) {
    $(Tabs).prev().attr('contenteditable', 'true').focus(); 
}

noteditable = function (Tabs) {
    $(Tabs).attr('contenteditable', 'false');
}

Fiddle Demo

  

问题:如何将光标放在最后?

1 个答案:

答案 0 :(得分:3)

试试此代码

$.fn.focusEnd = function() {
    $(this).focus();
    var tmp = $('<span />').appendTo($(this)),
        node = tmp.get(0),
        range = null,
        sel = null;

    if (document.selection) {
        range = document.body.createTextRange();
        range.moveToElementText(node);
        range.select();
    } else if (window.getSelection) {
        range = document.createRange();
        range.selectNode(node);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
    tmp.remove();
    return this;
}

http://jsfiddle.net/nikhilsreeni/K2Kun/3/