2 回答
TA贡献1820条经验 获得超10个赞
它完全适用于您的示例。该函数从给定的 Element 节点检索 Text 节点,因此请注意,如果给定的元素包含 Element 子元素(而不是直接文本内容),您必须根据需要调整该函数。
const el = document.getElementById('my-text-element');
selectWord(el, 'world');
function selectWord(element, word){
const textNode = element.childNodes[0]; //retrieve the Text node from the Element node
const selection = window.getSelection(); //get the Selection object
const range = document.createRange(); //create the Range object
const text = textNode.textContent; //retrieve the [string] from Text object
const startPosition = text.search(word); //now we look for the word in the [string] value
if(startPosition === -1) return; //if the word does not exist return and do nothing
const endPosition = startPosition + word.length; //we need start and end position to select the found word
range.setStart(textNode, startPosition); //it takes the Text node within we want to select some text, and we pass the starting character
range.setEnd(textNode, endPosition); //we pass the ending character in the same Text node
selection.addRange(range); //pass our prepared Range object and select the text
}
<p id="my-text-element">hello world</p>
TA贡献1773条经验 获得超3个赞
要选择元素的特定部分,该部分应该有自己的标签,然后您可以在 javascript 中选择
<p>Hello <span id = "xxx">world</span></p>
添加回答
举报