在Firefox中可编辑内容的换行错误

时间:2018-10-26 01:46:52

标签: javascript jquery firefox

我正在使用此代码段尝试修复Firefox以非常奇怪的方式处理换行符的“错误”。

但是,如果您通过在div中设置光标来选择div中的文本,然后按cmd + A / ctrl + A,然后按向右箭头键转到文本结尾,然后按回车键,您会得到错误{ {1}}。

我该如何解决?

另外,如果将光标放在文本的中间,然后按Shift + Enter,我希望它使文本模糊,但在此之前也要添加换行符。我知道为什么,但是应该在哪里放置if(shift)代码以使其正确执行?

IndexSizeError: Index or size is negative or greater than the allowed amount
$(document).on('keydown', 'div', function(e) {
  var nl = e.keyCode == 13;
  var shift = e.shiftKey;
  if (nl) {
    var sel, node, offset, text, textBefore, textAfter, range;

    sel = window.getSelection();

    // the node that contains the caret
    node = sel.anchorNode;

    // if ENTER was pressed while the caret was inside the input field

    // prevent the browsers from inserting <div>, <p>, or <br> on their own
    e.preventDefault();

    // the caret position inside the node
    offset = sel.anchorOffset;        

    // insert a '\n' character at that position
    text = node.textContent;
    textBefore = text.slice( 0, offset );
    textAfter = text.slice( offset ) || ' ';
    node.textContent = textBefore + '\n' + textAfter;

    // position the caret after that new-line character
    range = document.createRange();
    range.setStart( node, offset + 1 );
    range.setEnd( node, offset + 1 );

    // update the selection
    sel.removeAllRanges();
    sel.addRange( range );

    // Blur on shift+return
    if(shift) {
      $(this).blur();
    }
  }
});
div[contenteditable] {
	white-space: pre-wrap;
	overflow-wrap: break-word;
}

0 个答案:

没有答案