我想有一个句子/段落“我喜欢每天骑自行车”。等等,在该段落的上方应有类别:“名词”,“动词”等。当用户将鼠标悬停在“名词”上时,应使“自行车”和“天”发光并悬停在“动词”上“喜欢”和“骑”。我认为也许可以通过在特定单词周围使用span标签将类设置为“名词”或“动词”以及某种CSS和/或JS来完成。有人可以帮忙吗?
明确一点,这就是我在说的。
Nouns - Verbs
I like to ride my bicycle every day.
最佳答案
请尝试以下代码。我希望这有助于获得基本思路
function selectWords(name) {
let words = document.getElementById("words").children;
for (let i = 0; i < words.length; i++) {
if (words[i].className === name) {
words[i].classList.add("selected");
} else {
words[i].classList.remove("selected");
}
}
}
let selects = document.getElementsByClassName("select");
for (let i = 0; i < selects.length; i++) {
selects[i].addEventListener("mouseenter", function() {
selectWords(this.dataset.words);
});
selects[i].addEventListener("mouseleave", function() {
selectWords("empty");
});
}
.selected {text-shadow: 1px 1px 1px red}
<div id="words"><span>I</span> <span class="verb">like</span> <span class="verb">to ride</span> <span>my</span> <span class="noun">bicycle</span> <span>every</span> <span class="noun">day</span></div>
<div class="select" data-words="noun">Nouns</div>
<div class="select" data-words="verb">Verbs</div>
关于javascript - 将鼠标悬停在关键字上会使句子/段落中的某些单词发光,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48363166/