H5之contenteditable

场景:

<div id='content' contenteditable='true' >
hello </div> <button id='caret'>设置光标位置</button>

 

需求:点击按钮,把插入符放到文本‘hello’的后面或前面,像这样

//后面
hello|

//前面
|hello

并兼容主流浏览器

 

解决:

function placeCaret(el, atStart) {
  el.focus();

  if (typeof window.getSelection != 'undefined' && typeof document.createRange != 'undefined') { 

    var range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(atStart);

    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(atStart);
    textRange.select();
  }     
}

// true 为开始位置,false 为末尾
placeCaret( document.getElementById('content'), false );

 

参考:http://stackoverflow.com/questions/4233265/contenteditable-set-caret-at-the-end-of-the-text-cross-browser?lq=1

你可能感兴趣的:(H5之contenteditable)