设置背景图片与大小和不重复从文件夹中的随机图像

JavaScript: set background image with size and no-repeat from random image in folder

本文关键字:文件夹 图像 随机 背景图片 设置      更新时间:2023-09-26

我是一个javascript新手…我试图写一个函数,从目录抓取随机图像,并将其设置为我的横幅div的背景图像。我还需要设置图像的大小,并为它不重复。这是我目前得到的,它不太好用。我错过了什么?

$(function() {
// some other scripts here
  function bg() {
    var imgCount = 3;
    // image directory
    var dir = 'http://local.statamic.com/_themes/img/';
    // random the images
    var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
    // array of images & file name
    var images = new Array();
    images[1] = '001.png',
    images[2] = '002.png',
    images[3] = '003.png',
    document.getElementById('banner').style.backgroundImage = "url(' + dir + images[randomCount] + ')";
    document.getElementById('banner').style.backgroundRepeat = "no-repeat";
    document.getElementById('banner').style.backgroundSize = "388px";
  }
}); // end doc ready

我纠结了一段时间,我想出了这个解决方案。只要确保你在"banner"元素中有一些内容,这样它就会显示出来,因为只有一个背景不会给元素提供大小。

function bg() {
   var imgCount = 3;
   var dir = 'http://local.statamic.com/_themes/img/';
   // I changed your random generator
   var randomCount = (Math.floor(Math.random() * imgCount));
   // I changed your array to the literal notation. The literal notation is preferred.
   var images = ['001.png', '002.png', '003.png'];
   // I changed this section to just define the style attribute the best way I know how.
   document.getElementById('banner').setAttribute("style", "background-image: url(" + dir + images[randomCount] + ");background-repeat: no-repeat;background-size: 388px 388px");
}
// Don't forget to run the function instead of just defining it.
bg();

这是我使用的一些东西,它工作得很好。首先,我将所有的背景图片重命名为"1.jpg"。"29. jpg")。然后:

var totalCount = 29;
function ChangeIt() 
{
var num = Math.ceil( Math.random() * totalCount );
document.getElementById("div1").style.backgroundImage = 'images/'+num+'.jpg';
document.getElementById("div1").style.backgroundSize="100%";
document.getElementById("div1").style.backgroundRepeat="fixed";
}

然后运行ChangeIt()函数