使用 javascript 在悬停时突出显示重复的单词

Highlight Duplicate word on hover using javascript

我有以下html

<div class="my-div">
     <p>
        Hello from the moon        
     </p>
</div>
<div class="my-div">
     <p>
        Hello World
     </p>
</div>

是否可以使用 javascript,当我将鼠标悬停在第一个 div 中的单词 'Hello' 上时,我突出显示甚至加粗了 'Hello' 中的单词第二 div..

感谢任何帮助

要突出显示特定单词,您需要将其放在 <span> 标记中。例如:

 <div class="my-div">
        <p>
            <span class="first-hello">Hello</span> from the moon        
        </p>
    </div>
    <div class="my-div">
        <p>
            <span class="second-hello">Hello</span> World
        </p>
    </div>

在 JavaScript 文件中,您可以使用 document.querySelector() 函数 select 您的元素。然后添加适当的事件侦听器,在本例中,mousemove 在光标在元素内移动鼠标时触发,而 mouseout 在光标移出元素时触发

const firstHello = document.querySelector(".first-hello");
const secondHello = document.querySelector(".second-hello");

firstHello.addEventListener("mousemove", () => {
    secondHello.style.fontWeight = "bold";
});

firstHello.addEventListener("mouseout", () => {
    secondHello.style.fontWeight = "normal";
}); 

我正在使用 Lettering.jsJquery 来实现这一点。

<script src="jquery-3.5.1.js"</script>
<script src="lettering.js"></script>

<script>
function btnClicked(){

 //The words are now put into individual spans. See lettering js documentation
 $(".lettr").lettering('words');

 $("span").hover(function(e){

    // set default background color to white
    $("span").css("background-color", "white");

    //Get the word at the current mouse hover
    let word = e.target.innerHTML.trim();
    //Keep a list of all spans in the html document
    let listSpans = $("html").find("span");

    //Loop through all the individual spans and see if the innerHTML matches the word. If so , highlight it.
    for(let i=0;i<listSpans.length;i++){
        let spanword= listSpans[i].innerHTML.trim();

        if(spanword== word){
            $(listSpans[i]).css("background-color", "yellow");
        }
    }
    }, function (e) {

  });

}
</script>

这是我的body

<body>
<div>
    <p class="lettr"> Heloo i am </p>
    <p class="lettr">Heloo me too</p>
</div>

<button onClick="btnClicked();">Click me</button>
</body>