簡體   English   中英

jQuery fadein和fadeout同時出現

[英]jQuery fadein and fadeout simulaneously

我目前使用以下內容淡化我網站上的圖像:

$(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

如您所見,當前圖像必須在新圖像淡入之前淡出。

我希望這個行動是同時的。 請 - 有誰知道我怎么能做到這一點?

非常感謝。

編輯:無能的新手。 非常感謝代碼示例。

在實際的元素之上創建一個新的img元素,然后淡化這個新圖像。 你需要一些css來將新圖像放在舊圖像之上。

絕對不能只使用一個img元素。

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);

}

您也可能希望在開始淡入淡出之前等待加載新圖像。 (checkout jQuery doc用於正確的功能,並在加載回調中淡化圖像)。

這是Ulflander的想法的實現,因為發布的代碼不完整http://jsfiddle.net/8nBqD/1/

訣竅是絕對將第二張圖像放在你漸漸淡出的圖像之上

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM