1、准备好要用的图片;
2、开始操作;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>随机切换图片</title> </head> <body> <div style="width: 500px; height: 500px; margin: 50px auto;"> <img id="images" style="width: 500px; height: 500px;" src="https://so2.360tres.com/sdm/365_365_/t0168ced599efb911bc.webp" alt=""> </div> <div id="button" style="cursor: pointer; width: 100px;text-align: center;margin: 0 auto; padding: 10px; border: 1px solid black;">切换图片</div> <script> var images = document.getElementById('images'); //获取id为images的元素 var button = document.getElementById('button');//获取id为button的元素 //创建图片路径的数组 var img_list = [ "https://so2.360tres.com/sdm/664_417_/t01acb5ba04d757bdaf.webp", "https://so2.360tres.com/sdm/420_207_/t011dd85b56b9e2759d.webp", "https://so2.360tres.com/sdm/365_365_/t01b6a998ff60d26992.webp", "https://so2.360tres.com/sdm/420_627_/t011790205eea026469.webp", "https://so2.360tres.com/sdm/365_365_/t014d3e7793609ace60.webp", "https://so2.360tres.com/sdm/365_365_/t019fa90bd7858a6e58.webp", "https://so2.360tres.com/sdm/365_365_/t019fa90bd7858a6e58.webp", "https://so2.360tres.com/sdm/299_417_/t01d53be8e7f94b49fd.webp", "https://so2.360tres.com/sdm/417_417_/t0107e095b5c2d07495.webp", "https://so2.360tres.com/sdm/417_417_/t0133b95e60a2bb367a.webp", "https://so2.360tres.com/sdm/417_417_/t01ef441af5211d1960.webp", "https://so2.360tres.com/sdm/664_417_/t0111ac7b662effbfa1.webp", "https://so2.360tres.com/sdm/417_417_/t017ff7af43a92739a2.webp", "https://so2.360tres.com/sdm/365_365_/t0168ced599efb911bc.webp", ]; //给button绑定点击事件 button.onclick = function(){ var random = Math.floor(Math.random()*img_list.length);//创建随机整数 images.src = img_list[random];//以随机出来的整数作为img_list数组的下标来访问图片路径 } </script> </body> </html>