尝试传递单词并创建一个<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()
相同,但是要输入所需的值,而不是手动突出显示它。
任何建议将不胜感激!
答案 0 :(得分:2)
您可以尝试这种方法:
为了简单起见,我声明了这些常量。您也可以通过Network 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>
答案 1 :(得分:1)
这是一个小样本:)
您只需将其必须检查的根元素传递给该函数,然后,它只是一个基本的replace
函数!
const words = ['once', 'you'];
const highlight = (root, words) => {
words.forEach(word => {
root.innerHTML = root.innerHTML.replace(word, word => `<a class="highlighted">${word}</a>`);
});
};
highlight(document.querySelector('.root'), words);
.highlighted {
background-color: yellow;
}
<div class="root">
<p>Let's do a simple test for once.</p>
<p>Do you like tests?</p>
</div>