如何创建背景图像列表'URL,并使用jQuery在单击函数时应用它们

how can I create a list of background images' URLs and apply them on click function with jQuery?

本文关键字:jQuery 单击 函数 应用 URL 创建 何创建 背景 图像 列表      更新时间:2023-09-26

我希望从图像URL列表中提取HTML主体的背景图像,并在每次单击页面上的按钮时随机或按顺序(按顺序首选)应用一个新图像。

所以它必须是这样的:

var images = ["URL1", "URL2", "URL3"];
$("button").onclick(function(){
//choose a random/sequential image from var images and use it as a background image for my body
// on another click choose a different background-image from images and use it as background
// and so on
});

你可以随机地做这件事&next&上一篇:

var imagesArr = ["1.jpg","2.jpg"];
var selectedImage = 0;
$("button").click(function(){
  var item = imagesArr[Math.floor(Math.random()* imagesArr.length)];
  document.getElementById('body').style.backgroundImage = item;
});
$(".nextButton").click(function(){
   if(selectedImage < imagesArr.length){
      selectedImage++;
      document.getElementById('body').style.backgroundImage = imagesArr[selectedImage];
   }
});
$(".prevButton").click(function(){
   if(selectedImage > 1){
      selectedImage--;
      document.getElementById('body').style.backgroundImage = imagesArr[selectedImage];
   }
});