代码之家  ›  专栏  ›  技术社区  ›  warm__tape

如何将简单的淡入淡出动画添加到此JQuery图像交换?

  •  0
  • warm__tape  · 技术社区  · 5 年前

    我有以下结构和JQuery函数(基于 this ):

    var sourceSwap = function () {
        var $this = $(this);
        var newSource = $this.data('alt-src');
        $this.data('alt-src', $this.attr('src'));
        $this.attr('src', newSource);
    }
    
    $(function() {
        $('img[data-alt-src]').each(function() { 
            new Image().src = $(this).data('alt-src'); 
        }).hover(sourceSwap, sourceSwap);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" data-alt-src="https://images.pexels.com/photos/237018/pexels-photo-237018.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">

    我该如何添加一个简单的淡入淡出动画呢?现在只是一个瞬间的转变

    0 回复  |  直到 5 年前
        1
  •  1
  •   4b0 Agit    5 年前

    使用 .fadeTo()

    var sourceSwap = function() {
      var $this = $(this);
      var newSource = $this.data('alt-src');
      $this.data('alt-src', $this.attr('src'));
      $this.fadeTo(1000, 0.15, function() {
        $this.attr("src", newSource);
      }).fadeTo(200, 1);
    }
    
    $(function() {
      $('img[data-alt-src]').each(function() {
        new Image().src = $(this).data('alt-src');
      }).hover(sourceSwap, sourceSwap);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <img class="xyz" data-alt-src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
    <br/>
    <img class="xyz" data-alt-src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
    <br/>
    <img class="xyz" data-alt-src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
        2
  •  1
  •   Vishal modi    5 年前

    你可以用下面的方法 CSS

    #cf {
      position:relative;
      height:281px;
      width:450px;
      margin:0 auto;
    }
    
    #cf img {
      position:absolute;
      left:0;
      -webkit-transition: opacity 1s ease-in-out;
      -moz-transition: opacity 1s ease-in-out;
      -o-transition: opacity 1s ease-in-out;
      transition: opacity 1s ease-in-out;
    }
    
    #cf img.top:hover {
      opacity:0;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="cf">
    <img class="bottom" src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
    
    <img  class="top" src="https://images.pexels.com/photos/237018/pexels-photo-237018.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" >
    </div>