【问题标题】:synchronized hover of two different elements两个不同元素的同步悬停
【发布时间】:2021-03-20 04:07:49
【问题描述】:

我正在尝试在名为#front 的 div 中创建一个包含重复正文的网站。还有一个经典的body,命名为#back

我想做的是将鼠标悬停在两个不同的 div #front#back 上。因此,当只有一个链接时,这可以正常工作,但不是在您添加更多链接时,因为它会将效果应用于所有 a 而不仅仅是 您悬停的那个,它是对应的一个另一个div

例如: 我想将“amet”悬停在 #back 中以使“amet 在 #front 中具有相同的样式,但我不希望 #back#front 中的“其他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>

【问题讨论】:

    标签: javascript html jquery css hover


    【解决方案1】:

    要执行您需要的操作,您可以使用 :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>

    【讨论】:

    • 嗨,感谢您的帮助,但这并不是我真正想要的
    • 实际上,正如我所说,我希望#front#back 中的链接在悬停时具有相同的样式。所以这是有效的。但另一方面,我想避免让我的a all 产生这种效果。 (同时使用amet和其他amet)
    • 鉴于您的编辑,我更新了答案 - 希望这符合您的要求
    • 我为早期的混乱道歉 :) 祝你有个美好的夜晚
    猜你喜欢
    • 2017-01-21
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多