2 回答

TA貢獻1820條經驗 獲得超10個贊
它完全適用于您的示例。該函數從給定的 Element 節(jié)點檢索 Text 節(jié)點,因此請注意,如果給定的元素包含 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>
添加回答
舉報