Home >Web Front-end >JS Tutorial >How to Determine the Word Under the Cursor in JavaScript?
Given an HTML page containing text, how can you determine the word that the cursor is currently hovering over?
For Browsers that Support Shadow DOM (e.g., Chrome)
<code class="js">function getWordAtPoint(elem, x, y) { if (elem.nodeType === elem.TEXT_NODE) { // Create a range encompassing the element and determine offsets let range = elem.ownerDocument.createRange(); range.selectNodeContents(elem); let currentPos = 0; let endPos = range.endOffset; // Iterate through the characters until finding the one under the cursor while (currentPos + 1 < endPos) { range.setStart(elem, currentPos); range.setEnd(elem, currentPos + 1); let boundingClientRect = range.getBoundingClientRect(); if ( boundingClientRect.left <= x && boundingClientRect.right >= x && boundingClientRect.top <= y && boundingClientRect.bottom >= y ) { // Expand to word boundaries and return the text range.expand("word"); let result = range.toString(); range.detach(); return result; } currentPos += 1; } } else { // Recursively check child nodes for (let i = 0; i < elem.childNodes.length; i++) { range = elem.childNodes[i].ownerDocument.createRange(); range.selectNodeContents(elem.childNodes[i]); // Check if child node is under the cursor if ( range.getBoundingClientRect().left <= x && range.getBoundingClientRect().right >= x && range.getBoundingClientRect().top <= y && range.getBoundingClientRect().bottom >= y ) { range.detach(); // Recursively search the child node return getWordAtPoint(elem.childNodes[i], x, y); } else { range.detach(); } } } return null; }</code>
<code class="js">document.addEventListener("mousemove", (e) => { let word = getWordAtPoint(e.target, e.x, e.y); console.log("Word under cursor:", word); });</code>
The above is the detailed content of How to Determine the Word Under the Cursor in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!