javascript - 通过给它你想要它突出显示的单词来突出显示文本
问题描述
尝试传入文字并创建<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()
而是输入我想要的值,而不是手动突出显示它。
任何意见,将不胜感激!
解决方案
您可以尝试这种方法:
为简单起见,我已经声明了常量。您也可以通过网络 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>
推荐阅读
- r - 使用 panelAR 从 R 中的 Stata 重新创建 xtgls 回归
- reactjs - 光标重叠建议 - 小 ux 问题
- javascript - 如何允许在 Chart.js 工具提示中复制文本?
- php - Illuminate\Http\Response 类的对象无法转换为 int
- docker - 使用 docker-compose 构建多阶段 Dockerfile 时如何保留所有工件?
- angular - 使用 App_Initializer 从 .json 文件在运行时角度加载配置变量
- python-3.x - 提高具有多个条件的 Pandas 子集/过滤器的性能
- reactjs - 折线图上没有渲染注释线
- python - 接受整数或整数列表的 Python 函数
- report - 具有汇总值的 BIRT 报告图表