0

私は現在、自分のサイトの画像をフェードするために以下を使用しています。

$(document).ready(function() {
    $('ul.image-switch li').mouseover(function(e) {
    if (e.target.nodeName.toLowerCase() == 'a') return;

    var image_src = $('a', this).data('image');
    var img = $('.image-container img');

    if (img.attr('src') != image_src) { // only do the fade if other image is selected
        img.fadeOut(200, function() { // fadeout current image
            img.attr('src', image_src).fadeIn(200); // load and fadein new image
        });

    }
});
});​

この動作の例はhttp://www.sehkelly.com/#newsにあります。

ご覧のとおり、新しい画像がフェードインする前に、現在の画像がフェードアウトする必要があります。

同時動作をお願いします。お願いします-私がこれを達成する方法を誰かが知っていますか?

どうもありがとう。

編集:無知な初心者。コード例は非常に高く評価されています。

4

2 に答える 2

2

img実際の要素の上に新しい要素を作成し、この新しい画像をフェードインします。古いイメージの上に新しいイメージを配置するには、少し CSS が必要です。

img1つの要素だけでそれを行うことは決してできません。

if (img.attr('src') != image_src) { // only do the fade if other image is selected
    img.after(
        $('<img />').attr('src', image_src).fadeIn(200)
    );
    img.fadeOut(200);

}

フェードを開始する前に、新しい画像がロードされるのを待つこともできます。(そのための適切な関数についてjQueryドキュメントをチェックアウトし、ロードコールバックで画像をフェードします)。

于 2012-12-06T00:18:37.627 に答える
0

投稿されたコードが完全ではないため、Ulflander のアイデアの実装を次に示しますhttp://jsfiddle.net/8nBqD/1/

トリックは、フェードアウトしている画像の上に2番目の画像を絶対に配置することです

HTML

<img id='pic1' src="http://periodictable.com/Samples/009.3b/s7.JPG" />
<img id='pic2' src="http://icons.iconarchive.com/icons/vargas21/aquave-metal/256/Sample-icon.png" />

CSS

#pic2 {
   position: absolute;
   display: none;
}​

JS

// Fade out the image, and replace it with the new one after the fade is over
$("#pic1").fadeOut(500, function() { // fadeout current image
    this.src = 'http://icons.iconarchive.com/icons/vargas21/aquave-metal/256/Sample-icon.png';        
    $(this).show();
});

// Fade in the new image placing it on top of the original one
$("#pic2").offset($("#pic1").offset()).fadeIn(500, function(){
    // Hide it since we are showing the original image with the new src        
    $(this).hide();
});

これを簡単に再利用できるようにプラグインを作成することもできます

(function($) {
    $.fn.imageFader = function(newSrc, seconds) {
        $(this).each(function() {
            var $img = $(this);
            $img.fadeOut(seconds, function() {
                this.src = newSrc;
                $img.show();
            });
            var $tempImg = $('<img src="'+newSrc+'" style="position:absolute;display:none;" />').appendTo('body');
            $tempImg.offset($img.offset()).fadeIn(seconds, function(){
                $tempImg.remove();
            });
        });
    };
})(jQuery);

http://jsfiddle.net/8nBqD/5/のように使用します

$('img').imageFader('picture.png', 1000);
于 2012-12-06T00:37:06.460 に答える