如何用JavaScript高亮指定文本并获取"You will"的坐标?
Alright, let's break down your two JavaScript tasks step by step, based on the HTML structure you provided:
To highlight target words, we can wrap them in a styled <span> element by modifying the text content of the <text> node. Here's a straightforward implementation:
// Locate the target <text> element within the .highlight_content div const highlightContainer = iframeDoc.getElementsByClassName('highlight_content')[0]; const textElement = highlightContainer.querySelector('p > text'); // Cleaner selector approach // Define the word(s) you want to highlight const targetWord = "You will"; // Replace the target word with a highlighted span textElement.innerHTML = textElement.textContent.replace( new RegExp(targetWord, 'g'), // 'g' flag for global matches if needed `<span style="background-color: #ffeb3b; font-weight: bold;">${targetWord}</span>` );
If you prefer reusable styles, define a CSS class instead of inline styles:
.highlighted-text { background-color: #ffeb3b; font-weight: bold; }
Then update the replacement line to:
`<span class="highlighted-text">${targetWord}</span>`
The getBoundingClientRect() method on the entire <text> element gives you the element's bounds, not a specific text snippet. To get the coordinates of "You will", we need to use the Range API to target that exact text segment:
// Get the <text> element (using your original selector for consistency) const ele212 = iframeDoc.getElementsByClassName('highlight_content')[0].children[0].getElementsByTagName('p')[3].getElementsByTagName('text')[0]; const textNode = ele212.firstChild; // Access the actual text node inside <text> // Define the target text fragment const targetFragment = "You will"; // Find the start and end indices of the fragment in the full text const startPos = textNode.textContent.indexOf(targetFragment); const endPos = startPos + targetFragment.length; // Create a Range object and set it to the target fragment const textRange = document.createRange(); textRange.setStart(textNode, startPos); textRange.setEnd(textNode, endPos); // Get the bounding rect of the text fragment const fragmentRect = textRange.getBoundingClientRect(); console.log(fragmentRect); // Contains top, left, width, height, etc.
Note: If "You will" appears multiple times in the text, indexOf will only find the first occurrence. To handle multiple instances, you'd need to loop through all matches using a regular expression with the g flag.
内容的提问来源于stack exchange,提问作者Sunil kumar Chandela

