2017-01-14 147 views
0

我有下面的代碼:
我使用滑動滑塊來創建滑塊與背景圖像,而不是使用img標記。我的滑塊高度是700px,最小高度是400px。 隨着jQuery代碼下面我想改變背景圖像取決於窗口的寬度,但問題是,代碼只改變第一個滑塊的圖像。任何幫助? :)謝謝滑動滑塊更改bg圖像

<div class="hero-slider-wraper"> 
<div class="hero-slider"> 
    <div class="hero-slider-component"> 
    <div class="hero-slider-image" data-img-mobile="http://website.com/wp-content/uploads/2017/01/home1-small.jpg" data-img-large="http://website.com/wp-content/uploads/2017/01/home1.jpg" ></div> 
    <div class="hero-slider-image" data-img-mobile="http://website.com/wp-content/uploads/2017/01/home2-small.jpg" data-img-large="http://website.com/wp-content/uploads/2017/01/home2.jpg"></div> 
    <div class="hero-slider-image" data-img-mobile="http://website.com/wp-content/uploads/2017/01/home3-small.jpg" data-img-large="http://website.com/wp-content/uploads/2017/01/home3.jpg"></div> 
    </div> 
</div> 
</div> 

function resizeSlick() { 
    var desktopImage = $('.slick-current').attr("data-img-large"); 
    var mobileImage = $('.slick-current').attr("data-img-mobile"); 

if($(window).width() < 768) 
{ 
     $('.slick-current').css('background-image', 'url("'+ mobileImage +'")'); 
} 
else 
{ 
     $('.slick-current').css('background-image', 'url("'+ desktopImage +'")'); 
} 
} 

    //initialize 
    resizeSlick(); 

    //call when the page resizes. 
    $(window).resize(function() { 
     resizeSlick(); 
    }); 

回答

1

你需要運行的每個圖像的代碼,而不僅僅是.slick-current

function resizeSlick() { 
    var windowWidth = $(window).width(); 

    $('.hero-slider-image').each(function() { 
    var desktopImage = $('.slick-current').attr("data-img-large"), 
     mobileImage = $('.slick-current').attr("data-img-mobile"); 

    if (windowWidth < 768) { 
     $(this).css('background-image', 'url("' + mobileImage + '")'); 
    } else { 
     $(this).css('background-image', 'url("' + desktopImage + '")'); 
    } 

    }); 
} 

//initialize 
resizeSlick(); 

//call when the page resizes. 
$(window).resize(resizeSlick);