jQuery .toggleClass()转换

时间:2014-10-02 05:33:22

标签: jquery css css-transitions toggleclass

我正在编写一个jQuery脚本,使用.toggleClass()来改变悬停时img的不透明度,该类的css为:

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

它的问题是,当我移除鼠标时,我希望它转换回原始的不透明度,但由于切换类突然发生,我的代码是

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

任何想法?

我知道这一切都可以用css来完成,但是我试图用jQuery来推动自己学习新东西,因为我对它很陌生并喜欢挑战

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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);
        }
    );
});

答案 2 :(得分:0)

问题可能是当删除类时,transition属性也会丢失

&#13;
&#13;
jQuery(function($) {
  $(".port-item-img").hover(function() {
    $(this).toggleClass('img-hover');
  });
});
&#13;
.img-hover {
  opacity: 0.5;
}
.port-item-img {
  transition: opacity 3s;
}
&#13;
<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>
&#13;
&#13;
&#13;