简体   繁体   中英

Change image in document.body

I want to change the background of the html page with the following function:

<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>

But it wont. I know there is syntax error in document.body.src but can anyone tell me what is the correct way to change as the background image is coming through css.

the body does not have an attribute named src. try changing the style attribute:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM