繁体   English   中英

jquery 图像交换的淡入淡出过渡

[英]Fade transition for jquery image swap

我对 jquery 有点陌生,我有这个工作 function 可以交换列表元素的 hover 上的图像。 我正在尝试添加一个淡出和淡入,但它不起作用。 图像淡出,但它没有获得新图像的正确路径。
这是工作脚本:

$(document).ready(function() {
    var path = 'images/';
    $('.menu-child').hover(function() {
        var newimage = $(this).attr('data-path') + '.jpg';
        $('.swap > img').attr('src', path + newimage)
    });
});

这是我尝试的淡入淡出效果(以及一些变体,我都无法使用):

$(document).ready(function() {
    var path = 'images/';
    $('.menu-child').hover(function() {
    var newimage = $('.menu-child').attr('data-path') + '.jpg';
        $('.swap > img').fadeOut(function() {
            $('.swap > img').attr('src', path + newimage).fadenIn();
        });
    });
});

HTML:

<section class="submenuWrapper">
    <ul class="twinsub">
        <li class="twinmultisub twinleft">
             <ul>
                  <li class="menu-child" data-path="menu-interior"><a href="#"><span>Interior Painting</span></a></li>
                  <li class="menu-child" data-path="menu-exterior"><a href="#"><span>Exterior Painting</span></a></li>
             </ul>
        </li>
        <li class="twinmultisub twinimg">
             <section class="swap">
                 <img src="images/menu-exterior.jpg" />
             </section>
        </li>   
    </ul>
</section>

我们有几件事。

尝试这个:

$(document).ready(function() {
  var path = 'images/';
  $('.menu-child').hover(function() {
    var newimage = $(this).attr('data-path') + '.jpg';
    $('.swap > img').fadeOut(function() {
      $(this).attr('src', path + newimage).fadeIn();
    });
  });
});

工作示例: https://jsfiddle.net/sabrick/fudLgqxs/3/

您可能会自己弄清楚为什么它现在可以工作,但是如果您需要任何其他详细信息,请告诉我。

这是一个带有适当评论的示例

$(document).ready(function() {
    var path = 'images/';
    $('.menu-child').hover(function() {
        var newimage = $(this).attr('data-path') + '.jpg';
        if(newimage != (path + $('.swap > img').attr('src'))){
            /*if the current image being displayed is not the same
            as the data-path of the hovered element.
            This prevents it from running even when the image should
            not be changing
            */
            $('.swap > img').fadeOut(0);
            //first fade out the current image
            $('.swap > img').attr('src', path + newimage);
            //then change the path when it is not visible
            $('.swap > img').fadeIn(500);
            //then fade in the new image with the new path
        }
    });
});

暂无
暂无

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

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