赞
踩
目录
随便去网上找几张图片素材
- <!doctype html>
- <html>
-
- <head>
- <meta charset="utf-8">
- <title></title>
- </head>
-
- <body>
- <style>
- * {
- margin: 0;
- padding: 0;
- }
-
- #box {
- width: 500px;
- margin: 50px auto;
- padding: 10px;
- background-color: greenyellow;
- /* 设置文本居中 */
- text-align: center;
- }
- </style>
- <script type="text/javascript">
- // 带年纪按钮切换图片
- </script>
- <div id="box">
- <img src="img/1.jpg" alt="猫咪" />
- <button id="prev">上一张</button>
- <button id="next">下一张</button>
- </div>
- </body>
-
- </html>
添加JS代码,让它实现图片切换的功能
- <script type="text/javascript">
- // 带年纪按钮切换图片
- window.onload = function() {
- var prev = document.getElementById('prev');
- var next = document.getElementById('next');
- // 要想切换图片就要修改img标签的src属性
- var imgs = ['img/1.jpg','img/2.jpg','img/3.jpg',];
- var index = 0;
- var info = document.getElementById('info');
- info.innerHTML = '一共'+imgs.length+'张图片,现在第'+(index+1)+'张';
- prev.onclick = function(){
- var img = document.getElementsByTagName('img')[0];
- index--;
- // 判断索引是否超出图片数范围
- if(index<0){
- index = imgs.length-1;
- };
- img.src = imgs[index];
- info.innerHTML = '一共'+imgs.length+'张图片,现在第'+(index+1)+'张';
- };
- next.onclick = function(){
- var img = document.getElementsByTagName('img')[0];
- index++;
- if(index>imgs.length-1){
- index = 0;
- };
- img.src = imgs[index];
- info.innerHTML = '一共'+imgs.length+'张图片,现在第'+(index+1)+'张';
- };
- };
- </script>
- <!doctype html>
- <html>
-
- <head>
- <meta charset="utf-8">
- <title></title>
- </head>
-
- <body>
- <style>
- * {
- margin: 0;
- padding: 0;
- }
-
- #box {
- width: 500px;
- margin: 50px auto;
- padding: 10px;
- background-color: greenyellow;
- /* 设置文本居中 */
- text-align: center;
- }
- #img{
- width: 400px;
- height: 350px;
- }
- </style>
- <script type="text/javascript">
- // 带年纪按钮切换图片
- window.onload = function() {
- var prev = document.getElementById('prev');
- var next = document.getElementById('next');
- // 要想切换图片就要修改img标签的src属性
- var imgs = ['img/1.jpg','img/2.jpg','img/3.jpg',];
- var index = 0;
- var info = document.getElementById('info');
- info.innerHTML = '一共'+imgs.length+'张图片,现在第'+(index+1)+'张';
- prev.onclick = function(){
- var img = document.getElementsByTagName('img')[0];
- index--;
- // 判断索引是否超出图片数范围
- if(index<0){
- index = imgs.length-1;
- };
- img.src = imgs[index];
- info.innerHTML = '一共'+imgs.length+'张图片,现在第'+(index+1)+'张';
- };
- next.onclick = function(){
- var img = document.getElementsByTagName('img')[0];
- index++;
- if(index>imgs.length-1){
- index = 0;
- };
- img.src = imgs[index];
- info.innerHTML = '一共'+imgs.length+'张图片,现在第'+(index+1)+'张';
- };
- };
- </script>
- <div id="box">
- <p id="info"></p>
- <img id="img" src="img/1.jpg" alt="猫咪" />
- <div>
- <button id="prev">上一张</button>
- <button id="next">下一张</button>
- </div>
-
- </div>
- </body>
-
- </html>
点击按钮可以切换上一张和下一张
这节的JS图片切换的学习就告一段落!!!
上节学习内容链接:
感谢各位关注,一起加油!!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。