JS:点击按钮切换图片的小应用。
HTML:
<div id="div"> <p id="desc"></p> <!--默认显示第一张图片--> <img src="img/1.jpg" alt="加载失败" style="width: 800px;height: 400px;"> <button id="pre">上一张</button> <button id="next">下一张</button> </div>
CSS:
<style> * { margin: 0; padding: 0; } #div { width: 800px; height: 420px; margin: 20px auto; background-color: rgb(243, 119, 36); text-align: center; } button:hover { cursor: pointer; } </style>
JS:
<script> //预加载,等页面加载完毕后,再执行脚本 window.onload = function () { var num = document.getElementsByTagName("img")[0]; //这里虽然只有一个img标签,但是num变量的结果依然是一个数组 //定义图像地址 var shuzu = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg", "img/5.jpg", "img/6.jpg", "img/7.jpg", "img/8.jpg", "img/9.jpg", "img/10.jpg", "img/11.jpg", "img/12.jpg"]; //获取按钮 var prev = document.getElementById("pre"); var next = document.getElementById("next"); var index = 0; //图片描述 var p_desc = document.getElementById("desc"); p_desc.innerHTML = "一共" + shuzu.length + "张图片" + ",当前是第" + (index + 1) + "张"; //注意此处前面是字符串的拼接,实现加法需要用到括号 //点击切换图片 prev.onclick = function () { index--; //此处让它循环 if (index < 0) index = shuzu.length - 1; num.src = shuzu[index]; p_desc.innerHTML = "一共" + shuzu.length + "张图片" + ",当前是第" + (index + 1) + "张";//注意此处前面是字符串的拼接,实现加法需要用到括号 } next.onclick = function () { index++; if (index > shuzu.length - 1) index = 0; num.src = shuzu[index]; p_desc.innerHTML = "一共" + shuzu.length + "张图片" + ",当前是第" + (index + 1) + "张";//注意此处前面是字符串的拼接,实现加法需要用到括号 } }
网友评论文明上网理性发言 已有0人参与
发表评论: