I am developing a text editor for the web frontend, and I want to highlight the line where the text caret is located.
Normally, it should be quite simple to implement: just by listening to the selectionchange event and updating the position of the highlight block based on the DOMRect of the range.
The code as follows:
let edit = document.getElementById('edit'); let hLine = document.getElementById('highlightLine'); let selection = getSelection(); let y = hLine.getBoundingClientRect().y; document.addEventListener("selectionchange", (event) => { let range = selection.getRangeAt(0); let newTop = String(5 + range.getBoundingClientRect().y - y) + "px"; hLine.style.top = newTop; // console.log(range.getBoundingClientRect()); }); edit.addEventListener('focus', function(event) { hLine.style.opacity = "1"; }); edit.addEventListener('blur', function(event) { hLine.style.opacity = "0"; }); </script> #container { position: relative; } #edit { width: 200px; height: 200px; padding: 5px; font-size: 18px; overflow-wrap: break-word; white-space: pre-wrap; } #highlightLine { width: 200px; height: 25px; background-color: rgb(237, 237, 237); opacity: 0; position: absolute; z-index: -1; left: 5px; top: 5px; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Example</title> </head> <body> <article id="container"> <div id="edit" contenteditable="true">This is an example of this problem</div> <div id="highlightLine"></div> </article> </body> </html> But, there is a problem: If a physical line has a soft wrap, the DOMRect for the two positions at the wrap (the end of the previous line and the start of the next line) are identical.
This will result in the highlight block staying on the previous line if the caret is at the start of the next line (or possibly the other way around):
Please help, thank you.


"#highlightLine"do? Is it supposed to show the text that's supposed to be highlighted?#highlightLineis a div element used to display the background highlight of the current line. It is positioned absolutely to cover the current line in the text editor. It does not display text; instead, it acts as a background highlight to emphasize the current line.