The pre tag adds the contenteditable= "true" attribute, and the cursor is not visible when wrapping the line.

set the ctrl+enter line wrap, the line wrap method is to add"r"
at the cursor, but constantly wrapping the line will appear the cursor outside the visual window, the scroll bar does not follow the cursor scroll, what should be done? The code is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<pre contenteditable="true" style="width: 500px;height: 500px;border:1px -sharp000 solid;overflow-y: auto">
< / body > < script > Document.querySelector ("pre"). Onkeydown = function ($event) { Var keycode = window.event? $event.keyCode: $event.which; Var evt = $event | | window.event; / / enter--> send a message If (keycode = = 13 & &! (evt.ctrlKey)) { / / the code to send the message $event.preventDefault (); Return false; } / / ctrl+ enter--> Line break If (evt.ctrlKey & & evt.keyCode = = 13) { InsertContent ("\ r") Return false; } } Function insertContent (content) { If (! content) {/ / return if the insert is empty Return } Var sel = null; If (document.selection) {/ / IE9 below Sel = document.selection; Sel.createRange (). PasteHTML (content); } else { Sel = window.getSelection (); If (sel.rangeCount > 0) { Var range = sel.getRangeAt (0); / / get the selection range Range.deleteContents (); / / Delete the selected content Var el = document.createElement ("div"); / / create an empty div shell Window. = el; El.innerHTML = content; / / set the div content to what we want to insert. Var frag = document.createDocumentFragment (); / / create a blank document fragment so that you can insert the dom tree later Var node = el.firstChild; Var lastNode = frag.appendChild (node); Range.insertNode (frag); / / sets the content of the selection to be inserted Var contentRange = range.cloneRange (); / / Clone selection ContentRange.setStartAfter (lastNode); / / set the cursor position to the end of the insert ContentRange.collapse (true); / / move the cursor to the end Sel.removeAllRanges (); / / remove all selections Sel.addRange (contentRange); / / add a modified selection } } } < / script > < / html >

you just need to change the value of scrollTop every time you break a line.
pre.scrollTop = pre.scrollHeight

Menu