javascript html5 更改背景图片间隔时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13495186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:57:58  来源:igfitidea点击:

html5 change background image interval time

javascript

提问by zero_coding

How can i change body background image at interval time, for example, every 10 seconds should change the background image. it is possible with html5?
Thanks

如何在间隔时间更改正文背景图像,例如,每 10 秒应更改背景图像。可以用 html5 吗?
谢谢

回答by Shivam Gupta

You can use a javascript function for this and use the SetTimeOut in that function itself which will call the same function after the specified time interval.

您可以为此使用 javascript 函数,并在该函数本身中使用 SetTimeOut,它将在指定的时间间隔后调用相同的函数。

Try the following:

请尝试以下操作:

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
var imageID=0;
function changeimage(every_seconds){
    //change the image
    if(!imageID){
        document.getElementById("myimage").src="http://www.all-freeware.com/images/full/38943-nice_feathers_free_screensaver_desktop_screen_savers__nature.jpeg";
        imageID++;
    }
    else{if(imageID==1){
        document.getElementById("myimage").src="http://www.hickerphoto.com/data/media/186/flower-bouquet-nice_12128.jpg";
        imageID++;
    }else{if(imageID==2){
        document.getElementById("myimage").src="http://www.photos.a-vsp.com/fotodb/14_green_cones.jpg";
        imageID=0;
    }}}
    //call same function again for x of seconds
    setTimeout("changeimage("+every_seconds+")",((every_seconds)*1000));
}
</script>
</head>

<body style='background:black;' onload='changeimage(2)'>
<div style='position:absolute;width:100%;height:100%;left:0px;top:0px;' align='center'><img width='300px' height='250px' id='myimage' src='http://www.photos.a-vsp.com/fotodb/14_green_cones.jpg'/></div>
</body>

</html>

回答by enhzflep

Just by setting document.body.backgroundImage.

只需通过设置 document.body.backgroundImage 即可。

You can do this in a function that is called by either setInterval or setTimeout.

您可以在由 setInterval 或 setTimeout 调用的函数中执行此操作。