簡體   English   中英

jQuery fadeOut和fadeIn背景圖片

[英]jQuery fadeOut and fadeIn background-image

當我單擊某個鏈接時,我希望背景圖像淡出,更改為另一圖像,然后淡入。

我有的代碼:

$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').css('background-image', 'url('+image+')');
})

我嘗試了這個:

$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').fadeOut('3000').fadeIn('3000').css('background-image', 'url(' + image + ')');
})

但這沒有用,我在做什么錯? (我是jQuery新手)

編輯:

我用Rory McCrossan的答案解決了這個問題:

$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').fadeOut('3000', function() {
        $(this).css('background-image', 'url('+image+')').fadeIn('3000');
    });
});

但是,現在淡出到白色背景,然后淡入到圖像,給人一種閃爍的感覺嗎? 有沒有辦法加載圖像?

您需要在fadeOut完成后通過調用fadeIn鏈接淡化。 您可以通過使用回調函數參數來執行此操作。 嘗試這個:

$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').fadeOut('3000', function() {
        $(this).css('background-image', 'url('+image+')').fadeIn('3000');
    });
});

如果您添加/刪除具有所需圖像的div而不在后台進行任何更改,會不會更簡單? 只是一個例子:

 <div data-image="some-other-image.jpg" class="appendhere" style="position:relative">some content and an image background here</div>

現在使用jQuery,您可以將圖像放在上面數據屬性的頂部,不透明度為0,將其淡入和淡出:

 $('.link').on('click',function(){
   var image = $(this).data('image');
   var appendcode = '<div class="appended" style="display:none;position:absolute;width:200px;height:200px;overflow:hidden"><img src="' + image + '"></div>';
   $('#div-with-the-bgimage').append(appendcode);
   $('.appended').css({'opacity': 0, 'display':'block', 'z-index': 999}).fadeIn('3000', function() {
     $(this).fadeOut('3000');
   });
});

我在那里使用了一些內聯樣式,以指出您需要使包裝器相對定位並附加絕對位置,並且具有更高的z-index,您當然可以通過將它們包含在CSS中來使其更加優雅。

U可以結合animateopacity也可以使用fadeOutfadeIn函數。

查看此鏈接jsfiddle,以查看使用fadeOut和fadeIn的有效示例。

U還可以使用data-gallery屬性指定一個唯一的img標簽,該標簽存儲用於圖像的多個URL,以在所有圖像之間切換。 檢查其他鏈接jsfiddle以查看工作示例。 單擊按鈕切換以更改圖像。

希望它有用!

暫無
暫無

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

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