事件来修改同级元素

event to modify sibling element

本文关键字:元素 修改 事件      更新时间:2023-09-26

在一个网页中,我有一个div网格。在每个div中有3个div,第二个是隐藏的,我希望这样,当用户悬停在第三个div上时,第一个div会被隐藏,而第二个会被显示。

我正在使用jquery。

<div class="container">
  <div class="hello">hello</div>
  <div class="who">sailor
  </div>
  <div onmouseover="whoOn();" onmouseout="whoOff();" class="hover">hover me</div>
</div>
<div class="container">
  <div class="hello">hello</div>
  <div class="who">dolly
  </div>
  <div onmouseover="whoOn();" onmouseout="whoOff();" class="hover">hover me</div>
</div>
<div class="container">
  <div class="hello">hello</div>
  <div class="who">kitty
  </div>
  <div onmouseover="whoOn();" onmouseout="whoOff();" class="hover">hover me</div>
</div>

这是一个Codepen

您的whoOn和whoOff方法可以这样组合:

<div class="container">
  <div class="hello">hello</div>
  <div class="who">sailor
  </div>
  <div onmouseover="whoBoth(this);" onmouseout="whoBoth(this);" class="hover">hover me</div>
</div>

Javascript:

function whoBoth(target) {
  $(target).siblings(".hello, .who").toggle();
}