JavaScript:设置背景图像的大小和文件夹中随机图像的不重复

标签 javascript background-image

我是一个 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

最佳答案

我搞乱了这个问题一段时间,然后我想出了这个解决方案。只需确保“横幅”元素中有一些内容,以便它实际显示,因为仅背景不会为元素提供大小。

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();

关于JavaScript:设置背景图像的大小和文件夹中随机图像的不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24419370/

相关文章:

javascript - 使用堆叠布局时将自定义值字段映射到 x 值

javascript - 在 javascript eslint 中允许使用分号

css - div 背景 repeat-x 的问题

html - CSS 背景。将内容框与封面相结合

html - 如何在 Bootstrap 容器中将图像显示为背景

javascript - jQuery Ajax 文件上传

javascript - 增加滚动条的大小react-custom-scrollbar

javascript - Meteor.js 最有用的智能包是什么

html - CSS 中的 Base64 图标与多种用途的外部图像的性能

html - 提供背景图像和不透明度