2014-10-02 109 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>