[英]How to set caret to newly added element in contentEditable element?
I am working on a WYSIWYG editor in which I want to add <p>
's when hit Enter / Return key and then the user will write to this new <p>
. 我正在使用WYSIWYG编辑器,在其中按下Enter / Return键时要在其中添加
<p>
,然后用户将写入此新的<p>
。
Right now I am having issue setting the caret to this new <p>
. 现在,我在将插入符号设置为新的
<p>
时遇到问题。
$('#content').on('keypress', function(e){ if(e.which === 13){ console.log('enter pressed'); e.preventDefault(); var range = window.getSelection().getRangeAt(0); var element = document.createElement('p'); // element.textContent = 'lorem'; // gets added in the right position range.insertNode(element); // range.setStart(element); // doesn't work } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id='content' contentEditable=true>test</p>
I need to get this working in Chrome for now. 我现在需要在Chrome浏览器中正常运行。
How do I fix this? 我该如何解决?
A simple solution if you don't absolutely need the top contenteditable
element to be a p
element, is to add a contenteditable
div as parent of your p
element. 如果您不一定绝对需要top
contenteditable
元素作为p
元素,那么一个简单的解决方案是将contenteditable
div添加为p
元素的父级。 Enter will automatically add p
elements. Enter将自动添加
p
元素。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='content' contentEditable=true><p>test</p></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.