JavaScript通过变量修改CSS背景图片属性报错求助
问题分析与修复
你遇到的问题出在最后一行代码里:
document.getElementById("body-background").style.backgroundImage = 'url(url)';
这里的url被当成了字符串字面量,而不是你定义的变量,浏览器会尝试加载名为url的资源,自然找不到正确的背景图。
修复方案
有两种简单的修复方式:
- 使用模板字符串(推荐)
用反引号包裹字符串,变量用${}嵌入:
document.getElementById("body-background").style.backgroundImage = `url(${url})`;
- 字符串拼接
用加号把字符串和变量拼接起来:
document.getElementById("body-background").style.backgroundImage = 'url(' + url + ')';
代码优化(可选)
你的代码里finalname = fullnameofbackground.toString()是多余的,因为randombackground + ".jpg"已经是字符串类型了,可以直接去掉这一行,简化后的代码:
function changebackground() { let randombackground = Math.floor(Math.random() * 52) + 1; let url = `../bulkbackgrounds/${randombackground}.jpg`; console.log(url); document.getElementById("body-background").style.backgroundImage = `url(${url})`; }
内容的提问来源于stack exchange,提问作者Vibe Improvement
相关产品推荐
相关产品推荐

