更改文档.body中的图像

Change image in document.body

本文关键字:图像 body 文档      更新时间:2023-09-26

我想用以下函数更改html页面的背景:

<script type='text/javascript'>
var imageID=0;
function changeimage(every_seconds){
    //change the image
    if(!imageID){
        document.body.src="1.jpg";
        imageID++;
        alert(imageID++);
    }
    else{if(imageID==1){
        document.body.src="2.jpg";
        imageID++;
        alert(imageID++);
    }else{if(imageID==2){
        document.body.src="3.jpg";
        imageID=0;
        alert(imageID++);
    }}}
    //call same function again for x of seconds
    setTimeout("changeimage("+every_seconds+")",((every_seconds)*1000));
}
</script>

<body onload="hidemenu(); testPage(); changeimage(2)">
</body>

但它不会。我知道document.body.src中有语法错误,但有人能告诉我,当背景图像通过css时,更改的正确方法是什么吗。

主体没有名为src的属性。尝试更改样式属性:

document.body.setAttribute('style', 'background-image: url(1.jpg)');