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