简体   繁体   English

使用纯 javascript 而非 jQuery 防止 contenteditable 在输入时添加 div

[英]prevent contenteditable adding div on enter using pure javascript NOT jQuery

prevent contenteditable adding div on enter using pure javascript NOT jQuery使用纯 javascript 而非 jQuery 防止 contenteditable 在输入时添加 div

like this example http://jsfiddle.net/uff3M/像这个例子http://jsfiddle.net/uff3M/

but I need it in javascript not jQuery但我需要它在 javascript 而不是 jQuery

I solved my problem Thanks all我解决了我的问题 谢谢大家

 function enterToBr(e){ var evt = e || window.event; var keyCode = evt.charCode || evt.keyCode; if(keyCode==13){ document.execCommand('insertHTML', false, '<br>'); return false; } }
 div{ border:1px black solid; padding:10px; }
 <div contenteditable="true" id="container" onkeydown="enterToBr()"> When Enter it's create new div inside container , but I need when user press enter key create new br not new div </div>

Looks like all you still need to do, is properly prevent the event's default action - return false alone does not do that in this situation.看起来您仍然需要做的就是正确阻止事件的默认操作 - 在这种情况下,单独return false不会这样做。

You either need to pass this return value up the chain inside the HTML attribute used to add the handler function,您要么需要将此返回值向上传递到用于添加处理程序函数的 HTML 属性内的链中,

onkeydown="return enterToBr()"

or you prevent it using the appropriate method,或者您使用适当的方法阻止它,

    if(keyCode==13){
            document.execCommand('insertHTML', false, '<br>');
            evt.preventDefault();
    }

You can do that will CSS too.你也可以用 CSS 做到这一点。

Add display: inline-block;添加display: inline-block; to your div:到您的 div:

div{
    display: inline-block;
}

 function enterToBr(e){ var evt = e || window.event; var keyCode = evt.charCode || evt.keyCode; if(keyCode==13){ document.execCommand('insertHTML', false, '<br>'); } }
 div{ border:1px black solid; padding:10px; display: inline-block; }
 <div contenteditable="true" id="container" onkeydown="enterToBr()"> When Enter it's create new div inside container , but I need when user press enter key create new br not new div </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM