Memandangkan halaman HTML yang mengandungi teks, bagaimana anda boleh menentukan perkataan yang kursor sedang berlegar di atas?
Untuk Penyemak Imbas yang Menyokong Shadow DOM (cth., 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>
Atas ialah kandungan terperinci Bagaimana untuk Menentukan Perkataan Di Bawah Kursor dalam JavaScript?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!