2017-07-02 23 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