You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript高亮指定文本并获取"You will"的坐标?

Alright, let's break down your two JavaScript tasks step by step, based on the HTML structure you provided:

1. Highlight Specific Words in <p> Tags Under .highlight_content

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>`
2. Get Coordinates of the Text Fragment "You will"

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:37:18