2014-10-02 69 views
2

我寫一個jQuery腳本改變一個img的懸停使用.toggleClass()類的CSS是不透明度:jQuery的.toggleClass()過渡

.img-hover{ 
    opacity: 0.5; 
    transition: opacity 1s; 
} 

它的問題是,當我刪除我的鼠標我想它轉換回原來的不透明度,但它突然發生,因爲觸發類,我的代碼是

$(document).ready(function() { 
    $(".port-item-img").hover(function() { 
     $(this).toggleClass('img-hover'); 
    }); 
}); 

任何想法?

我知道這都可以在其自己的CSS這樣做,但我試圖強迫自己學習新事物與jQuery因爲我很新的,並喜歡挑戰

回答

1

只有jQuery的解決方案(沒有額外的CSS樣式)。

.animate()提供元素的動畫,.stop()用於在添加新動畫之前停止當前動畫(如果它仍在處理中)。

JSFiddle

$(document).ready(function() 
{ 
    $(".port-item-img").hover 
    (
     function() 
     { 
      $(this).stop().animate({ opacity: 0.5 }, 1000); 
     }, 
     function() 
     { 
      $(this).stop().animate({ opacity: 1 }, 1000); 
     } 
    ); 
}); 
+0

真棒!甚至不需要CSS,我只使用jQeury幾天,並且很好的愛它的能力! – 2014-10-02 05:48:34

+0

@ShoutItWebSolutions不客氣。使用CSS3而不是JS有時候更合適(工作更快等),但如果你想要一些非常自定義的東西,那麼JS和jQuery就是這樣。是的:jQuery有非常好的能力:) – Regent 2014-10-02 05:52:11

1

要使它耽誤你應該:

JS

$(document).ready(function() { 
    $(".port-item-img").hover(function() { 
     $(this).addClass('img-hover'); 
     $(this).removeClass('img-unhover'); 

    }, function() { 
     $(this).removeClass('img-hover'); 
     $(this).addClass('img-unhover'); 

    }); 
}); 

CSS

.img-unhover{ 
    opacity: 1; 
    transition: opacity 1s; 
} 
0

的問題可能是,當類被刪除的transition屬性也丟失

jQuery(function($) { 
 
    $(".port-item-img").hover(function() { 
 
    $(this).toggleClass('img-hover'); 
 
    }); 
 
});
.img-hover { 
 
    opacity: 0.5; 
 
} 
 
.port-item-img { 
 
    transition: opacity 3s; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="port-item-img">port-item-img</div> 
 
<div class="port-item-img">port-item-img</div> 
 
<div class="port-item-img">port-item-img</div>