[英]Keep on changing background colour without reloading page using JavaScript
我在使用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>
我面臨的問題是,每次需要更改背景顏色時,都需要重新加載它。 有什么方法可以自動保持自身的變化。
有什么方法可以自動保持自身的變化。
您可以在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>
現在無需在body onload
調用它。
演示版
function init() { var color = '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6); document.body.style.backgroundColor = color; setTimeout(init, 5000); } init();
您可以這樣:
<!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.