contenteditableelements allow users to edit text directly within the element. However, there can be cross-browser inconsistencies in how line breaks are handled.
contenteditableelements varies across browsers: Chrome places a
<div>within the line break, Firefox inserts a
<br />, and Internet Explorer adds a
<p>.
function placeCaretAtEnd(el) { el.focus(); if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") { var range = document.createRange(); range.selectNodeContents(el); range.collapse(false); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (typeof document.body.createTextRange != "undefined") { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(false); textRange.select(); } }
$(document).ready(function() { $('#insert_caret').click(function() { placeCaretAtEnd($('#content')); } });
The above is the detailed content of How to Place the Caret at the End of Text in a `contenteditable` Pre Element Consistently Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!