[英]Random background image in Javascript
here's my code: 这是我的代码:
function drawBgrImage() {
var random = Math.round(Math.random() * 8 + 1);
var folder;
var path;
if (window.innerWidth <= 768) {
folder = "xs";
} else if (window.innerWidth <= 1200) {
folder = "sm";
} else {
folder = "lg";
}
path = '"url(/wp-content/themes/BLANK-Theme/images/' + folder + '/' + random + '.jpg)"';
console.log(path);
document.getElementById("bgrImg").style.backgroundImage = path;
/*document.getElementById("bgrImg").style.backgroundImage = "url(/wp-content/themes/BLANK-Theme/images/lg/2.jpg)";*/
}
window.onload = drawBgrImage();
In folders xs, sm and lg I have 9 .jpg files. 在文件夹xs,sm和lg中,我有9个.jpg文件。 Function .drawBgrImage() is to draw a number from 1 to 9 and set image background on specified #bgrImg. .drawBgrImage()函数用于绘制1到9之间的数字,并在指定的#bgrImg上设置图像背景。 although var path returns the same value, as commented line it doesn't work. 尽管var path返回相同的值,但作为注释行却不起作用。
Any ideas? 有任何想法吗? Thanks in advance. 提前致谢。
It doesn't work because onload
should be a function, however you don't provide one. 它不起作用,因为onload
应该是一种功能,但是您没有提供。 It should be: 它应该是:
window.onload = drawBgrImage;
By putting parentheses after function name you invoke it immediately and assign window.onload
return value (which is undefined in your case). 通过在函数名称后加上括号,您可以立即调用它并分配window.onload
返回值(在您的情况下未定义)。
Another issue is that you wrapped path url into unnecessary quotes. 另一个问题是您将路径URL包裹在不必要的引号中。 Fix it like this: 像这样修复它:
path = 'url(/wp-content/themes/BLANK-Theme/images/' + folder + '/' + random + '.jpg)';
Replace: 更换:
path = '"url(/wp-content/themes/BLANK-Theme/images/' + folder + '/' + random + '.jpg)"';
with: 有:
path = 'url(/wp-content/themes/BLANK-Theme/images/' + folder + '/' + random + '.jpg)';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.