jQuery .addClass and .fadeIn?

jQuery .addClass and .fadeIn?

本文关键字:fadeIn and addClass jQuery      更新时间:2023-09-26

所以,我有这些 h1 元素是链接,我想向它们添加一个类,并在元素悬停后淡入该类,然后在 onMouseOut 删除该类,同时淡入类。但是使用淡入淡出功能对我没有任何作用。看到它隐藏了元素。有什么想法吗?

jQuery(".categories h1 a").hover(
function () {
    jQuery(this).fadeIn("slow").addClass("active");
},
function(){
    jQuery(this).fadeOut("slow").removeClass("active");
});
});

谢谢!

编辑:::

jQuery("h1").hover(function() {
      jQuery(this).stop().animate({ backgroundColor: "#a7bf51"}, 800);
      },function() {
      jQuery(this).stop().animate({ backgroundColor: "#FFFFFF"}, 800);
      });
});

尝试使用 jQuery UI .addClass 和 .removeClass。

$(function() {
    $(".categories h1 a").hover(function() {
        $(this).stop(true,true).addClass("active", 500);
    }, function() {
        $(this).stop(true,true).removeClass("active", 100);
    });    
});

DEMO(由于某种原因,它第一次不能正确(淡入淡出)动画......但后来它工作正常)

编辑:更新完整性。

您还可以使用.animate来获得所需的效果。见下文,

$(function() {
    $(".categories h1 a").hover(function() {
        $(this).stop().animate({
            backgroundColor: "#a7bf51"
        }, 800);
    }, function() {
        $(this).stop().animate({
            backgroundColor: "#FFFFFF"
        }, 800);
    });
});

演示

如果你不想

使用 jquery UI,因为它会是一个额外的负载,你可以执行以下操作:

(当我的应用程序中使用"隐藏"引导类时,对我很有用)

删除类时慢慢淡入:

$('.myClass').removeClass('hidden').fadeOut(0).fadeIn(10000)

慢慢淡出,添加类,然后淡入:

$('.myClass').fadeOut(1000, function(){
    $(this).addClass('hidden'); //or any other class
}).fadeIn(10000)

希望这会简化某人的任务!

听起来你希望类的样式淡入。你应该研究一下animate():http://api.jquery.com/animate/

入只是淡入元素。

我不认为你可以在类之间交叉淡入淡出,但你可以使用 animate 函数。 animate允许您在指定时间内影响任何 CSS 变量。

http://api.jquery.com/animate/

我知道这会从 css 文件中删除一些样式,但同样,我认为 jQuery 不会在类之间交叉淡入淡出。

如果你加载了jQuery UI库,你可以为toggleClass函数设置一个额外的参数。

通过 css 设置您的不透明度。

h1 a {
  opacity:0.8;
}
h1 a.hovered {
  opacity: 1.0;
}

然后

jQuery(".categories h1 a").hover(function(e) {
    $(this).toggleClass('hover', 1000);
}

1000 是事件的毫秒计数器。因此,当悬停在一秒时,效果应该淡入 1.0 不透明度,在不悬停时,效果应该在 1 秒内淡出。

试试这个,这里是jsFiddle(在这里输入链接描述):

<script type="text/javascript">
    jQuery(".categories h1").hover(function () {
            jQuery(this).stop().animate({ "background-color": "#a7bf51"}, 800);
            jQuery(this).addClass("active");
            jQuery(this).find("a").fadeIn("slow");
        },
        function() {
            jQuery(this).stop().animate({ "background-color": "#FFFFFF"}, 800);
            jQuery(this).addClass("active");
            jQuery(this).find("a").fadeOut("slow");
    });
</script>
<style type="text/css">
    .categories h1 {
        background-color: rgb(200, 200, 200);
        display: block;
        padding: 5px;
        margin: 5px;
        width: 100px
    }
    .categories h1 a {
        display: none;
    }
</style>
<div class="categories">
    <h1><a href="#">Item 1</a></h1>
    <h1><a href="#">Item 2</a></h1>
    <h1><a href="#">Item 3</a></h1>
</div>​