表示画像をクリックで用意した画像からランダム表示させます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ランダム画像切り替え</title>
<style>
body {
background: lightcyan;
color: darkgray;
}
img {
width: 400px;
cursor: pointer;
}
</style>
</head>
<body>
<center>
<img id="randomImage" src="pic/pic01.jpg"
alt="クリックで画像切替">
<h4>The character I created</h4>
<script>
const images = [
"pic/pic01.jpg",
"pic/pic02.jpg",
"pic/pic03.jpg",
"pic/pic04.jpg",
"pic/pic05.jpg"
];
const img = document.getElementById("randomImage");
img.addEventListener("click", () => {
const randomIndex =
Math.floor(Math.random() * images.length);
img.src = images[randomIndex];
});
</script>
</center>
</body>
</html>
picフォルダーに用意したs画像
実行直後はpic01.jpgを表示
画像をクリックでランダムに切り替わります。




