使用js更改背景图像
change background image using js
我无法在我的项目网站中更改 division 的背景图片。
我在 js 文件中使用此代码:
document.getElementsByClassName("home").style.backgroundImage = "url('../images/background4.jpg')";
我在 html 中的 div 是:
<div id="intro" class='home' align='center'>
我的 js 文件也位于 project/js/script.js
图片位于 project/images/background4.jpg
index.html 在 project/index.html
我找不到错误!
编辑
我也试过了document.getElementById()
但这也行不通。
基本路径上下文由索引定义,而不是script.js(不是PHP):
// index.html = ./project/
// execute index.html/js/script.js
// loading index.html/images/background4.jpg
document
.getElementsByClassName('home')[0]
.style
.backgroundImage = "url('images/background4.jpg')";
在您的浏览器中检查 DevTools:Network(右键单击:检查)。
祝你有美好的一天。
您必须使用 document.getElementById('intro')
而不是 getElementsByClassName('home')
来定位您的 div。
getElementsByClassName
returns 元素的集合,而不是一个元素。
编辑:是的,正如 Evehne 所说,路径应该是 "images/",而不是像在 css 文件中那样的“../images”。
我无法在我的项目网站中更改 division 的背景图片。 我在 js 文件中使用此代码:
document.getElementsByClassName("home").style.backgroundImage = "url('../images/background4.jpg')";
我在 html 中的 div 是:
<div id="intro" class='home' align='center'>
我的 js 文件也位于 project/js/script.js
图片位于 project/images/background4.jpg
index.html 在 project/index.html
我找不到错误!
编辑
我也试过了document.getElementById()
但这也行不通。
基本路径上下文由索引定义,而不是script.js(不是PHP):
// index.html = ./project/
// execute index.html/js/script.js
// loading index.html/images/background4.jpg
document
.getElementsByClassName('home')[0]
.style
.backgroundImage = "url('images/background4.jpg')";
在您的浏览器中检查 DevTools:Network(右键单击:检查)。
祝你有美好的一天。
您必须使用 document.getElementById('intro')
而不是 getElementsByClassName('home')
来定位您的 div。
getElementsByClassName
returns 元素的集合,而不是一个元素。
编辑:是的,正如 Evehne 所说,路径应该是 "images/",而不是像在 css 文件中那样的“../images”。