设置背景图片与大小和不重复从文件夹中的随机图像
JavaScript: set background image with size and no-repeat from random image in folder
我是一个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()
函数
相关文章:
- 如何将乳胶配方奶粉图像保存到Asp.net中的文件夹中
- 在ng重复循环中显示来自不同文件夹的图像
- 如何通过资产管道提供Javascript中子文件夹中的图像
- 可在多个相册文件夹中查找的动态图像库
- 如何使用javascript从文件夹中获取图像并发布直接链接
- Yii2从js脚本的页面上添加来自供应商文件夹的图像、css、js文件
- 如何在PHP中使用url保护我的图像和文件夹免受直接访问
- 使用文件夹路径名保存所有图像文件和文件名
- 将图像输出到浏览器,然后再将其保存到文件夹
- jQuery:用文件夹中的图像填充数组.或者使用AJAX从文件夹加载图像
- 将样式表、javascript和图像分离到不同文件夹中的优势
- 使用javascript从磁盘中的文件夹中选择所有图像的路径
- 如何从本地文件夹(磁盘存储)读取或获取图像文件,并使用nodejs服务器将其发送到Angularjs
- Dropzone.js没有将图像上传到文件夹
- 如何使用javascript获取文件夹中的图像列表
- 将文件夹中的所有图像包括在阵列中的最佳方式是什么
- Android 引用 JavaScript 文件中的资产文件夹图像
- jQuery日期选择器上一个和下一个按钮没有显示,如何指向css中的主题文件夹图像
- 我如何读取文件夹图像和显示html内
- 在Canvas中循环遍历文件夹图像