Jquery动画。 显示没有css没有变化

在页面的第一次加载中,图像必须显示:none 。 但问题是,当我将display none设置为无效时,animate函数无效,我已经将.css({‘display’:’block’})仍然无法正常工作。

这是我的代码

 $(document).ready(function() { $("img.fade").hover(function() { $(this).stop().animate({ "opacity": "1" }, 300); $(this).css({ 'display': 'block' }); }, function() { $(this).stop().animate({ "opacity": "0" }, 300); }); });   img.fade { display:none }   

如果我删除display:none样式,它正在工作但是当页面首次加载时,图像显示。 我需要在第一次加载时将其隐藏,然后在hover时显示。

如果隐藏的东西你不能将鼠标hover在它上面,因为它在页面中不占用任何空间。 而是最初将它的opacity设置为0。 删除您的CSS,您可以这样做:

 $(document).ready(function() { $("img.fade").hover(function() { $(this).stop().animate({ opacity: 1 }, 300); }, function() { $(this).stop().animate({ opacity: 0 }, 300); }).css({ opacity: 0 }); }); 

你可以在这里测试一下 。 或者,删除.css({ opacity: 0 }); 并将您的CSS更改为:

 img.fade { opacity: 0; filter: alpha(opacity=0); } 

你可以在这里测试那个版本 。

 $(this).css({'display':'block'}); == $(this).show(); $(this).stop().animate({"opacity": "0"}, 300); == $(this).fadeOut(300); 

等等

更改

 $("img.fade").hover( 

 $("img.fade").hide().hover( 

/ E:

并删除样式