[英]Keep on changing background colour without reloading page using JavaScript
I'm facing a problem while changing the background colour using js. 我在使用js更改背景颜色时遇到问题。
<!DOCTYPE html>
<html>
<head>
<title>First Js</title>
</head>
<body onload="init();">
</body>
<script type="text/javascript">
function init() {
var color = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
document.body.style.backgroundColor = color;
}
</script>
</html>
The problem I'm facing is that, everytime I need to change the background color I need to reload it. 我面临的问题是,每次需要更改背景颜色时,都需要重新加载它。 Is there any way by which it automatically keeps on changing itself.
有什么方法可以自动保持自身的变化。
Is there any way by which it automatically keeps on changing itself.
有什么方法可以自动保持自身的变化。
You can call init
method using setTimeout
by the end of init
method itself 您可以在
init
方法本身结束时使用setTimeout
调用init
方法
<script type="text/javascript">
function init() {
var color = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
document.body.style.backgroundColor = color;
setTimeout( init, 5000 ); //once done, call it back again after 5 sec
}
init(); //call this once
</script>
No need to call it in body onload
now. 现在无需在
body onload
调用它。
Demo 演示版
function init() { var color = '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6); document.body.style.backgroundColor = color; setTimeout(init, 5000); } init();
You can do like this: 您可以这样:
<!DOCTYPE html> <html> <head> <title>First Js</title> </head> <body onload="init();"> </body> <script type="text/javascript"> function init() { var color = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6); document.body.style.backgroundColor = color; } setInterval(function(){ init(); },1000); </script> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.