水曜日, 2月 07, 2024

Let's start JavaScript 21 
背景色を2秒ごとにランダム変更

背景色を2秒ごとにランダム変更してみます。

<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Random Change Background Color</title>
<style>
body {
transition: background-color 1s ease;
/*transitionプロパティにて、
 背景色の変更が1秒で滑らかに行われるように*/
}
</style>
</head>
<body>
<script>
function changeBackgroundColor() {
// ランダムなRGB値を生成
var randomColor = '#' +
Math.floor(Math.random()*16777215).toString(16);
// 背景色を変更
document.body.style.backgroundColor = randomColor;
}
// 初回の呼び出し
changeBackgroundColor();
// 2秒ごとに背景色を変更(1秒は1000)
setInterval(changeBackgroundColor, 2000);
</script>
</body>
</html>
<!-- index.html -->

ランダムでもいい感じでした。