gpt4 book ai didi

javascript - 通过给它你想要突出显示的单词来突出显示文本

转载 作者:太空宇宙 更新时间:2023-11-03 22:25:38 25 4
gpt4 key购买 nike

尝试传入单词并创建 <a>标记并将属性样式设置为黄色,基本上突出文本。我在 words.appendChild(newNode); 上遇到错误有谁知道我如何创建 <a> tag 用风格就定的话?

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() 相同的操作而是输入我想要的值,而不是手动突出显示它。

如有任何建议,我们将不胜感激!

最佳答案

你可以试试这个方法:

为了简单起见,我声明了常量。您也可以通过网络 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>

关于javascript - 通过给它你想要突出显示的单词来突出显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51363662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com