两个不同元素的同步悬停

synchronized hover of two different elements

我正在尝试在名为 #front 的 div 中创建一个具有重复 body 的网站。还有经典的body,名字叫#back.

我想做的是同步悬停在两个不同的 divs #front#back 上。因此,当只有一个链接时效果很好,但是一旦添加更多链接就不会这样,因为它会将效果应用于所有 a 而不仅仅是 你悬停的那个和在另一个div.

中是对应的

例如: 我想将 #back 中的“amet”悬停在 #front 中以相同的样式显示“amet”,但我不想在 #back#front 中显示“other amet”同款

我想知道这是否可以在元素上没有 ids 的情况下完成,但如果不是,那也很好。 感谢您的帮助!

$("a").on({
    mouseenter: function () {
     
    $("#front a, #back a").css({
    "font-style": "italic"
    })
    },
    mouseleave: function () {
   
    $("#front a, #back a").css({
    "font-style": "normal"
    })
    }
});
.scroll {
  position: absolute;
  display: block;
  top: 0;
  height: 100%;
 
}
#front {
  overflow: hidden;
  position: absolute;
  background-color: grey;
  color: white;
  right: 0;
  left: 0;
  bottom: 0;
  top: 0;
  margin: auto auto auto auto;
  width: 25%;
  height: 35%;
  font-size: 2rem;
}
#back {
  overflow: auto;
  font-size: 2rem;
}

p {
  margin: 0;
  padding: 0;
}

a:hover{
  font-style: italic;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="scroll" id="back">
  <a href="#">amet</a> &
  <a href="#">other amet</a>
</div>

<div class ="scroll" id="front">
  <a href="#">amet</a> &
  <a href="#">other amet</a>
</div>

要执行您需要的操作,您可以使用 :nth-child 在各自的容器中按索引关联两个元素。试试这个:

$("a").on('mouseenter mouseleave', e => {
  let index = $(e.target).index();
  $(`#front a:nth-child(${index + 1}), #back a:nth-child(${index + 1})`).css('font-style', e.type == 'mouseenter' ? 'italic' : 'normal')
});
.scroll {
  position: absolute;
  display: block;
  top: 0;
  height: 100%;
}

#front {
  overflow: hidden;
  position: absolute;
  background-color: grey;
  color: white;
  right: 0;
  left: 0;
  bottom: 0;
  top: 0;
  margin: auto auto auto auto;
  width: 25%;
  height: 35%;
  font-size: 2rem;
}

#back {
  overflow: auto;
  font-size: 2rem;
}

p {
  margin: 0;
  padding: 0;
}

a:hover {
  font-style: italic;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="scroll" id="back">
  <a href="#">amet</a> &amp;
  <a href="#">other amet</a>
</div>

<div class="scroll" id="front">
  <a href="#">amet</a> &amp;
  <a href="#">other amet</a>
</div>