JavaScript_DOM学习篇_图片切换小案例

今天开始学习DOM操作,下面讲一个小案例来巩固下知识点.

DOM: document object model (文档对象模型)

根据id获取页面元素 : 如: var xx = document.getElementById("id");

根据标签获取元素: 如: var xx = document.getElementsByTagName("div");

src="imgs/1.png"/><br> <button id="btn1" type="button" value="
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #outer {
            width: 500px;
            /*设置上边距50px 水平居中*/
            margin: 50px auto;
            /*设置边框*/
            padding: 10px;
            background-color: greenyellow;
            /*设置文本居中*/
            text-align: center;
        }
img { width: 500px; } </style>

<script>
     //btn 为按钮id clickEventFunction
为点击后执行的操作函数 function addClick(btn, clickEventFunction) { var myButton = document.getElementById(btn); myButton.onclick = clickEventFunction; }; window.onload = function () { (function () { var pics = ["imgs/1.png", "imgs/2.png", "imgs/3.png"]; var index = 0; showPicNum(index); var img = document.getElementsByTagName("img")[0]; // var btn1 = document.getElementById("btn1"); var btn2 = document.getElementById("btn2"); addClick("btn1", function () { index--; if (index <= -1) { index = pics.length - 1; } console.log(index + " ----- "); img.src = pics[index]; showPicNum(index); }); addClick("btn2", function () { index++; if (index >= pics.length) { index = 0; } console.log(index + " ++++++++ "); img.src = pics[index]; showPicNum(index); }); // // btn1.onclick = function () { // index --; // if(index <= -1){ // index = pics.length - 1; // } // console.log(index + " ----- "); // img.src = pics[index]; // showPicNum(index); // }; // btn2.onclick = function () { // index ++; // if(index >= pics.length){ // index = 0; // } // console.log(index + " ++++++++ "); // img.src = pics[index]; // showPicNum(index); // }; console.log(index); /** * 展示当前图片为第几张 * @param index 当前图片索引 */ function showPicNum(index) { var descrs = document.getElementById("discs"); descrs.innerText = "一共" + pics.length + "张图片,当前第" + ++index + ""; } }()) }; </script> </head> <body> <div id="outer"> <p id="discs"></p> <img src="imgs/1.png"/><br> <button id="btn1" type="button" value="上一张">上一张</button> <button id="btn2" type="button" value="下一张">下一张</button> </div> </body> </html>
 
 

文档目录:                                  效果如下:

               

上一张">上一张</button> <button id="btn2" type="button" value="下一张">下一张</button></div></body></html>

猜你喜欢

转载自www.cnblogs.com/ifeil/p/9342796.html