首页 > 解决方案 > 通过给它你想要它突出显示的单词来突出显示文本

问题描述

尝试传入文字并创建<a>标签并将属性样式设置为黄色,基本上突出显示文本。我在words.appendChild(newNode);“有谁知道我可以如何创建一个<a>带有设置字样样式的标签?”时出现错误?

highlightText(words) {
  // words contains 4 different words.
  const newNode = document.createElement('a');
     newNode.setAttribute(
       'style',
       'background-color: yellow; display: inline;'
     );
     words.appendChild(newNode);
     // words.surroundContents(newNode);
}

在过去,这是我所做的,但这是使用window.getSelection().

 highlightSelection() {
      this.complexWordIdentification(this.postIWant, this.theHardWords);
      const userSelection = window.getSelection();
      if (userSelection.toString() === null) {
         return;
      } else {
        for (let i = 0; i < userSelection.rangeCount; i++) {
            this.highlightRange(userSelection.getRangeAt(i));
            this.word = userSelection.toString();
        }
      }
    }


    highlightRange(range) {
        const newNode = document.createElement('a');
        newNode.setAttribute(
           'style',
           'background-color: yellow; display: inline;'
        ),
        range.surroundContents(newNode);
    }

我希望能够执行与函数相同的操作,highlightSelection()而是输入我想要的值,而不是手动突出显示它。

任何意见,将不胜感激!

标签: javascripthtmlcss

解决方案


您可以尝试这种方法:

为简单起见,我已经声明了常量。您也可以通过网络 API 调用引入单词并将单词传递给highlight方法。

const words = ['Lorem', 'ipsum'];

const getWords = async () => {
	//Use API calls here or simply define pass in Constants
  highlight(words);
}

const highlight = (words) => {
	const high = document.getElementById('highlight')
  const paragraph = high.innerHTML.split(' ');
  let res = [];
  
  paragraph.map(word => {
    let t = word
    if(words.indexOf(word) > -1){ 
      t = '<a class="high">' + word + '</a>'
    }
    res.push(t)
  })
  high.innerHTML = res.join(' ')
}

window.onload = getWords();
.high{
  background-color: yellow; 
  display: inline;
  margin-right: 5px;
}
<div >
  <p id="highlight">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio odio voluptas tempora voluptates expedita quo, nemo sint ipsa similique aliquid doloribus accusamus commodi amet id adipisci eos, inventore in consectetur.
  </p>
</div>


推荐阅读