我是 JavaScript 的新手,当时我正在做一个简单的元素。基本上我有一个 HTML 文档,我想在每次打开它时将背景图像更改为来自位于“背景”的目录中的随机图片。
function main()
{
// Creates a list of filenames from the 'Background/' dir and gets a
// random index in the list
var fs = require('fs');
var fileList = fs.readdirSync('/Background/');
var len = fileList.length;
var index = Math.floor(Math.random() * len);
var filePath = "Background/" + fileList[index];
document.body.style.backgroundImage = "url(filePath)";
document.body.style.backgroundSize = "cover"
}
$(document).ready(main);
无论出于何种原因,它似乎都不起作用。我无法确切地弄清楚 URL 类是如何工作的,因为我认为它与此有关。我没有收到任何错误。执行此操作时,我将背景图像更改为特定图像:
document.body.style.backgroundImage = "url('Background/green.jpg')";
但当我尝试随机检索文件名时却没有。 我确定这只是对语言或其他东西的误解,但我似乎无法弄清楚。谢谢。
最佳答案
您不能在浏览器中以这种方式使用 fs。您需要存储图像路径。您可以将它们存储在数据库中或 javascript 文件中的数组中。下面的示例将文件名存储在数组中。
function main()
{
var images = ['image1.jpeg', 'image2.jpg', 'bg.png'] //storing only names
var index = Math.floor(Math.random() * images.length)
var filePath = "Background/" + images[index]; //creating full path
document.body.style.background = 'url("'+filePath+'")'
// if background-size is not changing, it's better to store it in .css file
}
$(document).ready(main);
关于javascript - 使用 JavaScript 从文件名列表更改 HTML 文档的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49455667/