2017-07-02 42 views
0

我想在hr元素上实现一个效果。当用户悬停在徽标上时,我希望下面hr元素的宽度变为100%,并添加一些不透明度。jQuery和'这个'问题

当前所有hr元素同时发生变化。我该如何做到这一点,只有图像在变化上徘徊?

这是我的代码目前

$('.img-fluid').hover(function(){ 
    $(this).animate({ 
     opacity:0.5 
     },200); 
    $('.logo').animate({ 
     width:'100%' 
    },200); 

}, 
function(){ 
    $(this).animate({ 
     opacity:1 
     },200); 
    $('.logo').animate({ 
     width:'50%' 
    },200); 
}); 

$('.img-fluid').hover(function(){ 
    $('.logo',this).animate({ 
     width:'100%' 
    },200); 
}, function(){ 
    $('.logo',this).animate({ 
     width:'50%' 
    },200); 

}); 

HTML:

<div class="row col-md-11 mx-auto"> 
    <div class="col-md-2 mx-auto"> 
     <img src="images/logos/lyle_scott.png" class="img-fluid"> 
     <hr class="logo"> </div> 
    <div class="col-md-2 mx-auto"> 
     <img src="images/logos/makser.jpg" class="img-fluid"> 
     <hr class="logo"> </div> 
    <div class="col-md-2 mx-auto"> 
     <img src="images/logos/maxfli.jpg" class="img-fluid"> 
     <hr class="logo"> </div> 
    <div class="col-md-2 mx-auto"> 
     <img src="images/logos/mizuno.png" class="img-fluid"> 
     <hr class="logo"> </div> 
    <div class="col-md-2 mx-auto"> 
     <img src="images/logos/odyssey.jpg" class="img-fluid"> 
     <hr class="logo"> </div> 
    </div> 

此外,我想就能下来缩短这个代码,并在一个函数执行这一切。目前每个效果都是分开处理的。

见一个更好的主意这一形象:https://i.stack.imgur.com/mSIdj.png

+0

'logo'是您给'hr'元素的CSS类吗?请提供HTML代码。我们无法从图像中猜出它。 – trincot

+0

你可以添加html代码,所以我们可以知道元素和他们的类 – Dij

+0

嗨,在那里添加它。 – Darren

回答

0

如果您只是在选择器中使用该类,则将选择具有相同类的所有元素。在这种情况下,您需要使用jQuery .siblings()方法来获取正确的hr元素,因为hr与图像位于相同的级别/与父元素相同。

$(".img-fluid").on("mouseenter", function() { 
    $(this).animate({ 
     opacity:1 
    },200); 
    $(this).siblings('.logo').animate({ 
     width:'100%' 
    },200); 
}); 
$(".img-fluid").on("mouseleave", function() { 
    $(this).animate({ 
     opacity:0.5 
    },200); 
    $(this).siblings('.logo').animate({ 
     width:'50%' 
    },200); 
}); 
+0

这是完美的,谢谢。此外它的不错方式是将不透明度设置得更低,然后在悬停时更高或更亮。没有想到这一点:) – Darren

0

我不知道你的HTML的结构,但我认为你悬停在一个img-fuild类,那么你有它里面的标志元素。

$(".img-fluid").on("mouseover", function() { 
     $(this).animate({ 
      opacity:0.5 
      },200); 
     $(this).find('.logo').animate({ 
      width:'100%' 
     },200); 
    }); 
0

如果可以,我可以使用css而不是jQuery来使用动画或转换。使用:悬停,你不必担心试图只影响单个元素,因为这已经是它的工作原理。

+0

是的我知道我可以使用CSS来实现这一点,但我刚刚开始学习jQuery,所以我认为这样做会更有益处。 – Darren