semi-xi / blog

blog
4 stars 1 forks source link

contenteditable元素的焦点获取问题 #12

Open semi-xi opened 7 years ago

semi-xi commented 7 years ago

一般对于这类元素的获取,用focus跟blur是可以监听的,但是如果需要innerHTML这类的话,那样当前的焦点就会消失,并且使用focus()会无效。

解决办法如下:

//需要现代浏览器的支持
var p = document.getElementById('contentEditableElementId'),
    s = window.getSelection(),
    r = document.createRange();
r.setStart(p, 0);
r.setEnd(p, 0);
s.removeAllRanges();
s.addRange(r);

如果元素是空的话可以这样

var p = document.getElementById('contentEditableElementId'),
    s = window.getSelection(),
    r = document.createRange();
p.innerHTML = '\u00a0';
r.selectNodeContents(p);
s.removeAllRanges();
s.addRange(r);
document.execCommand('delete', false, null);

具体参考contenteditable焦点解决

semi-xi commented 7 years ago

在回车的时候,会增加一个<div>,解决的办法是这样

$('div[contenteditable]').keydown(function(e) {
    // trap the return key being pressed
    if (e.keyCode === 13) {
      // insert 2 br tags (if only one br tag is inserted the cursor won't go to the next line)
      document.execCommand('insertHTML', false, '<br><br>');
      // prevent the default behaviour of return key pressed
      return false;
    }
  });

详细见[这里](http://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome ,'')