第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

選擇 HTMLElement 的特定文本

選擇 HTMLElement 的特定文本

嗶嗶one 2022-11-27 17:12:39
在關(guān)于該方法的官方文檔中,Selection.addRange()當(dāng)我有特定范圍時,我可以選擇元素,但我不知道如何獲取作為文本一部分的特定單詞/目標(biāo)的范圍例子:<p>Hello world</p>我想添加范圍選擇,world就像我用鼠標(biāo)光標(biāo)手動標(biāo)記它一樣。另外:如何選擇特定文本并根據(jù)某些正則表達式規(guī)則對其進行標(biāo)記?到目前為止,我找不到關(guān)于 SO 的答案。官方 Mozilla 文檔addRange():https ://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange
查看完整描述

2 回答

?
拉莫斯之舞

TA貢獻1820條經(jīng)驗 獲得超10個贊

它完全適用于您的示例。該函數(shù)從給定的 Element 節(jié)點檢索 Text 節(jié)點,因此請注意,如果給定的元素包含 Element 子元素(而不是直接文本內(nèi)容),您必須根據(jù)需要調(diào)整該函數(shù)。


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>


查看完整回答
反對 回復(fù) 2022-11-27
?
慕容3067478

TA貢獻1773條經(jīng)驗 獲得超3個贊

要選擇元素的特定部分,該部分應(yīng)該有自己的標(biāo)簽,然后您可以在 javascript 中選擇

<p>Hello <span id = "xxx">world</span></p>


查看完整回答
反對 回復(fù) 2022-11-27
  • 2 回答
  • 0 關(guān)注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號