简体   繁体   English

更改图像src jQuery动画

[英]Change image src jquery animation

I'm changing an image on hover using JS, and would like to add a fading animation to it. 我正在使用JS更改鼠标悬停时的图像,并想为其添加淡入淡出的动画。 I've tried added .fadeToggle(), but nothing is working correctly. 我尝试添加.fadeToggle(),但是没有任何正常工作。

 $("document").ready(function(){ $(".logo_container").mouseenter(function(){ $("#logo").attr('src',function(index, attr){ return attr.replace(".png", "-color.png"); }); }); $(".logo_container").mouseleave(function(){ $("#logo").attr('src',function(index, attr){ return attr.replace("-color.png",".png"); }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="logo_container"> <img src="https://ironhorseclub.wpengine.com/wp-content/uploads/2018/05/logo2-sm.png" alt="Wordpress Install" id="logo" data-height-percentage="100"> </div> 

You can do this with just CSS: 您可以使用CSS来做到这一点:

 img:hover { opacity: 0.5; transition: opacity 0.3s linear; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="logo_container"> <img src="https://ironhorseclub.wpengine.com/wp-content/uploads/2018/05/logo2-sm.png" alt="Wordpress Install" id="logo" data-height-percentage="100"> </div> 

Just change the opacity value, the time value, and/or the easing-type to whatever you want. 只需将不透明度值,时间值和/或缓动类型更改为所需的值即可。

You can use jQuery fadeTo 您可以使用jQuery fadeTo

$( "img" ).hover(function(){ 
$(this).fadeTo( "slow" , 0.5, function() {
// Animation complete.
});
});

I recommend achieving the same using only CSS 我建议仅使用CSS实现相同的目标

 .logo_container { height:172px; width:403px; display:inline-block; background-image: url("https://ironhorseclub.wpengine.com/wp-content/uploads/2018/05/logo2-sm.png"); -webkit-transition: background-image 2s ease-out; -moz-transition: background-image 2s ease-out; -o-transition: background-image 2s ease-out; transition: background-image 2s ease-out; } .logo_container:hover { background:url("https://ironhorseclub.wpengine.com/wp-content/uploads/2018/05/logo2-sm-color.png") no-repeat center; } 
 <div class="logo_container"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM