javascript悬停在一个元素上会改变另一个元素

javascript-hovering one element changes other

本文关键字:元素 改变 另一个 一个 悬停 javascript      更新时间:2023-09-26

我希望悬停一个元素会影响另一个元素。在这篇文章中,我想在悬停某个div部分时,在其他div的图像中创建动画。为此,我使用了以下代码:

HTML:

<div class="s">hover here</div>
<section>
  <div class="hs-wrapper">
    <img src="images/1.gif" alt="image01"/>
    <img src="images/2.gif" alt="image02"/>
  </div>
</section>

JavaScript:

$(document).ready(function () {
    $(".s").mouseenter(function () {
          $(".hs-wrapper img").css({
        -webkit-animation-play-state:running;
       -moz-animation-play-state: running;
        -o-animation-play-state: running;
         -ms-animation-play-state: running;
         animation-play-state: running; 
        });
      $(".s").mouseleave(function () {
        $(".hs-wrapper img").css({
        -webkit-animation-play-state: paused;
         -moz-animation-play-state: paused;
          -o-animation-play-state: paused;
          -ms-animation-play-state: paused;
           animation-play-state: paused;    
         });
       });

但它不起作用。请提供建议。

根据您提供的标记,您不需要jQuery。

只需使用选择器.s:hover + section .hs-wrapper img。使用相邻的同级组合子+,当鼠标悬停在.s上时,可以选择下一个section元素。从中选择子img元素。

section .hs-wrapper img {
    -webkit-animation-play-state: paused;
    -moz-animation-play-state: paused;
    -o-animation-play-state: paused;
    -ms-animation-play-state: paused;
}
.s:hover + section .hs-wrapper img {
    -webkit-animation-play-state:running;
    -moz-animation-play-state: running;
    -o-animation-play-state: running;
    -ms-animation-play-state: running;
    animation-play-state: running;
}

下面是一个基本示例

section .hs-wrapper img {
    opacity:0;
    transition: 3s ease-out; /* Mouseleave */
}
.s:hover + section .hs-wrapper img {
    opacity:1;
    transition: .5s ease; /* Mouseenter */
}