【问题标题】:Change image src jquery animation更改图像src jquery动画
【发布时间】:2018-10-25 20:29:07
【问题描述】:

我正在使用 JS 更改悬停时的图像,并想为其添加一个淡入淡出的动画。我尝试添加 .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>

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

您只需使用 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>

只需将不透明度值、时间值和/或缓动类型更改为您想要的任何值。

【讨论】:

    【解决方案2】:

    你可以使用 jQuery fadeTo

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

    【讨论】:

      【解决方案3】:

      我建议只使用 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;
      }
      &lt;div class="logo_container"&gt;&lt;/div&gt;

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      相关资源
      最近更新 更多