如何在更改img时添加淡入淡出效果

时间:2014-02-22 16:16:31

标签: jquery

我在点击时会看到一系列图片,需要两件事:

1)当前图像淡出,新图像淡入(参见演示,点击前进)

2)如果不止一次点击按钮,防止点击增加..我想我需要使用.stop()这个我只是不知道如何。

这是一个jsfiddle:http://jsfiddle.net/8Y6dq/2/

HTML

<figure>
    <img src="coast.png" />
    <figcaption>Photography</figcaption>
    <nav>
        <a href="#">Back</a>
        <a href="#">Forward</a>
    </nav>
</figure>

的jQuery

$(function(){
    var images = [
        "water.png",
        "view.png",
        "sunset.png",
        "coastal.png"
    ],
        $img = $("figure img"),
        $i = 0,
        $j = images.length,
        $back = $("nav a").first(),
        $forward = $("nav a + a");


    $forward.click(function(){
        $i = ($i + 1) % images.length;
        $img.fadeOut().prop("src", images[$i]).fadeIn();
    });

    $back.click(function(){
        $j -= 1;
        if($j >= 0) {
            $img.prop("src", images[$j]);
        } else {
            $j += $j + 1;
        }
    });    

});

2 个答案:

答案 0 :(得分:2)

尝试

$(function () {
    var images = [
        "http://linenwoods.com/test/water.png",
        "http://linenwoods.com/test/view.png",
        "http://linenwoods.com/test/sunset.png",
        "http://linenwoods.com/test/coastal.png"],
        $img = $("figure img"),
        $i = 0,
        $back = $("nav a").first(),
        $forward = $("nav a + a"),
        flag = false;

    //preload all the images
    $.each(images, function (i, src) {
        new Image().src = src;
    })

    $forward.click(function () {
        //return if already a transition is in progress
        if (flag) {
            return;
        }
        $i = ($i + 1) % images.length;
        //start the switch animation
        swicth();
    });

    $back.click(function () {
        //return if already a transition is in progress
        if (flag) {
            return;
        }
        $i -= 1;
        //rollback to last if the current image is the first one
        if ($i < 0) {
            $i = images.length;
        }
        //start the switch animation
        swicth();
    });

    function swicth() {
        //set the flag to true to indicate a transition
        flag = true;
        $img.fadeOut(function () {
            //use a callback to change the src so that the fade in will be visible
            $img.prop("src", images[$i]).fadeIn(function () {
                //set the flag to false to indicate end of transition
                flag = false;
            });
        });
    }

});

演示:Fiddle

答案 1 :(得分:1)

我已将您的代码更新为仅用于前向链接

jsfiddle.net/8Y6dq/3/

我在那里添加了jquery版本。当用户点击链接一次并检查它以解决第二个问题时,还会添加课程