简体   繁体   中英

Display different sizes image in mobile tablet and desktop resolution using jquery

I am using Vegas slide for the full-width banner image with shuffle function on page reload/refresh.

How do I set cropped image for three different sizes like Desktop, tablet, and mobile with single variable.?

Below is my code, I have achieved using below code. but am calling function simultaneously, I guess it's not good practice to achieve. Anyone suggest me a better solution.

// The Shuffle Function
  function shuffle(o) { 
    for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
  };  

  // Define backgrounds array
  var bgimages = [{
      src: "images/dbg1.jpg"
    },
    {
      src: "images/dbg2.jpg"
    },
    {
      src: "images/dbg3.jpg"
    },
  ]

  var tabimages = [{
      src: "images/tablet/tbg1.jpg"
    },
    {
      src: "images/tablet/tbg2.jpg"
    },
    {
      src: "images/tablet/tbg3.jpg"
    },
  ]

  var mobimages = [{
      src: "images/mobile/mbg1.jpg"
    },
    {
      src: "images/mobile/mbg2.jpg"
    },
    {
      src: "images/mobile/mbg3.jpg"
    },
  ]

  var windowWidth = $(window).width();
  if ($(window).width() >= 1024) {
   // Suffle the array
    randombgs = shuffle(bgimages);
    $("body").vegas({
      delay: 10000,
      cover: true,
      timer: false,
      slides: randombgs
    });   
  }

  if ($(window).width() >= 768) {
   // Suffle the array
    randomTbg = shuffle(tabimages);
    $("body").vegas({
      delay: 10000,
      cover: true,
      timer: false,
      slides: randomTbg
    });
  }

  if ($(window).width() <= 767) {
   // Suffle the array
    randomMbg = shuffle(mobimages);
    $("body").vegas({
      delay: 10000,
      cover: true,
      timer: false,
      slides: randomMbg
    });
  }
$(window).resize(function() {
  var windowWidth = $(window).width();
  if ($(window).width() >= 1024) {
    randombgs = shuffle(bgimages);
  } else if($(window).width() >= 768) {
    randomTbg = shuffle(tabimages);
  } else {
    randomMbg = shuffle(mobimages);
  }
  $("body").vegas({
    delay: 10000,
    cover: true,
    timer: false,
    slides: randombgs
  });   
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM