光滑滑块更改bg图像

时间:2017-01-14 22:37:39

标签: javascript jquery css

我有以下代码:
我使用光滑的滑块来创建带有背景图像的滑块,而不是使用img标签。我的滑块高度为700px,最小高度为400px。 使用下面的jquery代码我想根据窗口宽度更改背景图像,但问题是代码只更改了第一个滑块的图像。有帮助吗? :)谢谢

<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 个答案:

答案 0 :(得分: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);