在Contenteditable Div中输入密钥的行为

时间:2013-11-13 09:43:47

标签: javascript html

我正在尝试创建一个富文本编辑器,我已经接近成功了。我试图在contenteditable div中更改enter键的行为,因为当按下输入firefox生成<br>即可,但Chrome和IE生成了<p><div>这里我正在尝试在<br>下按Enter键时强制所有浏览器生成<div contenteditable="true"></div>。 Internet Explorer中的所有工作正常但在所有浏览器中都必须按两次new line<br>

这是我的代码。

<!doctype html>
<html>
<head>
<title>Rich Text Editor</title>
<script type="text/javascript">
function preview() {
    var textbox = document.getElementById('textBox');
    document.getElementById("view").innerHTML=textbox.innerHTML;
}
function enterKeyPressHandler(evt) {
    var sel, range, br, addedBr = false;
    evt = evt || window.event;
    var charCode = evt.which || evt.keyCode;
    if (charCode == 13) {
        if (typeof window.getSelection != "undefined") {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
                br = document.createElement("br");
                range.insertNode(br);
                range.setEndAfter(br);
                range.setStartAfter(br);
                sel.removeAllRanges();
                sel.addRange(range);
                addedBr = true;
            }
        } else if (typeof document.selection != "undefined") {
            sel = document.selection;
            if (sel.createRange) {
                range = sel.createRange();
                range.pasteHTML("<br>");
                range.select();
                addedBr = true;
            }
        }
        // If successful, prevent the browser's default handling of the keypress
        if (addedBr) {
            if (typeof evt.preventDefault != "undefined") {
                evt.preventDefault();
            } else {
                evt.returnValue = false;
            }
        }
    }
}
function onload(){
    var el = document.getElementById("textBox");
    if (typeof el.addEventListener != "undefined")
    {
        el.addEventListener("keypress", enterKeyPressHandler , false);
    }
    else if (typeof el.attachEvent != "undefined")
    {
        el.attachEvent("onkeypress", enterKeyPressHandler);
    }
}
</script>
</head>
<body onload="javascript:onload();">
<form name="myform" method="POST">
<div id="textBox" contenteditable="true" style="width:500px; height:150px; padding:20px; border:solid thin #000"></div>
</form>
<br>
<div id="view" style="width:500px; height:150px; padding:20px; border:solid thin #000"></div>
<br>
<button onClick="javascript:preview();">Preview</button>
</body>
</html

演示 JSFiddle

2 个答案:

答案 0 :(得分:0)

IT工作!!!

&#13;
&#13;
if (window.getSelection) {
  var selection = window.getSelection(),
  range = selection.getRangeAt(0),
  br = document.createElement("br");
  
  range.deleteContents();
  
  range.insertNode(br);
  var newLine=document.createTextNode('\n');
  
  range.setStartAfter(br);
  range.setEndAfter(br);
  
  range.insertNode(newLine);

  selection.removeAllRanges();
  selection.addRange(range);
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我的解决方案是处理输入按钮。不同标签的不同选项。看https://codepen.io/MaratKh/pen/oKXxvV

> klr_predict
    [1] 0.7577828 0.7577828 0.7577828 0.7577828 0.7577828 0.7577828 0.7577828     0.7577828 0.7577828 0.7577828 0.7577828
const ed = document.getElementById('editable'),
      ta = document.getElementById('txt');

const key13 = function(ev){
  
  if(ev.keyCode==13) {
    ev.preventDefault();
    const selection = window.getSelection(),
        range = selection.getRangeAt(0),
        node = document.getSelection().anchorNode,
        pNode = node.parentNode;
  var tag = pNode.nodeName.toUpperCase();
  switch(tag) {
      case 'P':
        tag = 'BR';
      break;

      case 'DIV':
        tag = 'p';
      break;

      case 'SPAN':
        tag = 'span';
      break;

      case 'BR':
        tag = NULL;
      break;

      default:
        tag = 'BR';

    }

    const el = document.createElement( tag );

    range.deleteContents();
    range.insertNode(el);

    if ('BR'===tag) {
      range.setStartAfter(el);
      range.setEndAfter(el);
    } else {
      range.setStart(el, 0);
      range.setEnd(el, 0);
    }

    const ze = document.createTextNode("\u200B");
    range.insertNode(ze);
    range.setStartBefore(ze);
    range.setEndBefore(ze);

    selection.removeAllRanges();
    selection.addRange(range);
    ev.stopPropagation();
  }
  
  ta.value = ed.innerHTML;
}

ed.addEventListener( 'keydown', key13, false);
.xrow {
  display: block;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  justify-content: space-between;
}
.xrow .col {
  display: block;
  flex: 1;
}
  
.xrow .col:first-child{
    border-right:#669 1px dashed;
    margin-right:20px;
}

textarea {
  width:100%;
  height:300px;
}

#editable{
  padding:16px 9px;
  border: 2px dashed #ddc;
}