今天開始學習DOM操作,下麵寫一個小案例來鞏固下知識點. DOM: document object model (文檔對象模型) 根據id獲取頁面元素 : 如: var xx = document.getElementById("id"); 根據標簽獲取元素: 如: var xx = documen ...
今天開始學習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>