首页 > 解决方案 > jquery随机背景 - 不同的eveytime

问题描述

我将随机背景设置为 div。我想知道当背景改变时是否有可能每次都会显示不同的背景,而不是从我的图像目录中复制。

非常感谢任何帮助。

$(function() {
  var images = ['1.png', '2.png', '3.png'];
  $('#sectionhero').css({
    'background-image': 'url(bgimages/' + images[Math.floor(Math.random() * images.length)] + ')'
  });
});

标签: jqueryrandombackground

解决方案


你可以使用cookies来做到这一点,

https://github.com/js-cookie/js-cookie

$(function() {
  var images = ['https://cdn.pixabay.com/photo/2017/09/14/11/13/water-2748657_960_720.png', 'https://images.panoramatours.com/pt/focus/49/50/1536/648/user_upload/Sehenswuerdigkeiten/Salzburg/Schloss_Leopoldskron__c__Panorama_Tours.jpg', 'https://media.studioatrium.pl/project/1030/willa-panorama-ii-wizualizacja-1350-5954e6b4080d8.jpg'];
  if (Cookies.get('randomBackground') == undefined) {
    Cookies.set('randomBackground', 0); // if there's no cookie, it will display the first image
  } else {
    // if there's cookie, get a new one
    var randomBackground = getRandomBackground();
    Cookies.set('randomBackground', randomBackground);
  }
  $('#sectionhero').css({
    'background-image': 'url(' + images[Cookies.get('randomBackground')] + ')'
  });

  function getRandomBackground() {
    var rand = Math.floor(Math.random() * images.length);
    // if the value is the same as existing cookie value, get another one
    if (rand == Cookies.get('randomBackground')) return getRandomBackground();
    else {
      return rand;
    }
  }
});

推荐阅读