javascript 突出显示在DOM上找到的单词

4c8rllxm  于 2023-03-16  发布在  Java
关注(0)|答案(2)|浏览(113)

在我的vue应用程序中,我有一个方法来搜索DOM中的单词并滚动到第一个结果,但是我还想突出显示在DOM中找到的单词,我该怎么做呢?
我的搜索方法:

search() 
    { 
        const matches = document.querySelectorAll("body*:not(script):not(style):not(title)"); 

        for (let i = 0; i < matches.length; i++) 
        { 
        const element = matches[i]; 
        if (element.textContent.includes(searchTerm)) 
        { 
            if(i == 0)
            {
                element.scrollIntoView();
            }
            console.log('Found'); 
        } 
    }

先谢了

jhiyze9q

jhiyze9q1#

我想这个解决方案应该对你有用。

const searchTerm = 'example';
const matches = document.querySelectorAll('body *:not(script):not(style):not(title)');
let firstMatch = null;

for (let i = 0; i < matches.length; i++) {
  const node = matches[i];
  const nodeText = node.textContent;

  if (nodeText.includes(searchTerm)) {
    const newNodeText = nodeText.replace(new RegExp(searchTerm, 'g'), `<span class="highlight">${searchTerm}</span>`);
    node.innerHTML = newNodeText;
    if (firstMatch === null) {
      firstMatch = node;
    }
  }
}

if (firstMatch !== null) {
  firstMatch.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

对于CSS突出显示类

.highlight {
  background-color: yellow;
  color: black;
}
6g8kf2rb

6g8kf2rb2#

我认为您可以简单地使用内联CSS:

function search(searchTerm) { 
    const matches = document.querySelectorAll("p"); 

    for (let i = 0; i < matches.length; i++) { 
        const element = matches[i]; 

        if (element.textContent.includes(searchTerm)) { 
            if (i == 0) {
                element.scrollIntoView();
            }
            console.log('Found'); 
        }

        /* Highlight substring */
        element.innerHTML = element.innerHTML.replace(searchTerm, `<span style='background-color: #FFFF00'>${searchTerm}</span>`)
    }
}```

相关问题