您的位置:首页 > Web前端 > JavaScript

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

2019-03-28 11:01 483 查看

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

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

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

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

<!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>

文档目录:

效果如下:

以上所述是小编给大家介绍的JavaScriptDOM图片切换小案例详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: