var bgimages ='myImage.png'
var pathToImg=new Array(), i=0
pathToImg[0]=new Image()
pathToImg[0].src=bgimages
document.body.background=pathToImg[i].src
//以上作品 但是,当我尝试将“body”元素更改为 id 为“slide”的“DIV”时,它失败了,仅供引用,此 div 存在
document.getElementById('slide').style.background-image = pathToImg[i].src
或者动态设置 DIV 背景的正确语法是什么?
谢谢。
- 补充,完整代码
// image slideshow script 2
var bgimages=new Array()
bgimages[0]="paper-n.jpg"
bgimages[1]="kn-n.png"
// bgimages[2]="img3.jpg"
//preload images
var pathToImg=new Array()
for (i=0;i<bgimages.length;i++){
pathToImg[i]=new Image()
pathToImg[i].src=bgimages[i]
}
var inc=-1
function bgSlide(){
if (inc < bgimages.length-1)
inc++
else
inc=0
// document.body.background=pathToImg[inc].src
document.getElementById('slide').style['background-image'] = pathToImg[inc].src
// "url('" + pathToImg[i].src + "')";
}
if (document.all||document.getElementById)
window.onload=new Function('setInterval("bgSlide()",3000)')
// slideshow
body {
/*Remove below line to make bgimage NOT fixed*/
background-attachment:fixed;
background-repeat: no-repeat;
/*Use center center in place of 300 200 to center bg image*/
background-position: 300 200;
}
<div id="slide"></div>
最佳答案
使用[]
而不是.
更改样式
,如下所示:
document.getElementById('slide').style['background-image'] = pathToImg[i].src;
关于javascript - 这个 DIV 背景图像分配有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39109691/