开发者

JS/jQuery : Amend contents of div contenteditable and refocus

My Aim:

To be able to add/amend the content inside my content editable user input div on 开发者_C百科'keyup' and be able to refocus it so that the user is not interupted.

My Problem:

Content Editable div fails to properly refocus.

My Example:

http://jsbin.com/owoto4/4/


I have come up with a solution that is more effective than the .focus() method:

  $.fn.placeCaretAtEnd = function(){
    var el = $(this)[0];
    el.focus();
    if (typeof window.getSelection != "undefined"
      && typeof document.createRange != "undefined") {
      var range = document.createRange();
      range.selectNodeContents(el);
      range.collapse(false);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
      var textRange = document.body.createTextRange();
      textRange.moveToElementText(el);
      textRange.collapse(false);
      textRange.select();
    }
  }

USAGE:

$('#myContenteditable').placeCaretAtEnd();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜