JavaScript实现轮播图方法一
多个DIV,所有的DIV都由JavaScript生成,每个DIV的className均为photo,再通过数组来操控每个DIV的display属性
效果展示
主要代码
JavaScript
let Maximum = 8;
function generateElement()//给body添加div
{
let body = window.document.getElementById("body");
let photoDiv;
for (let i = 0; i < Maximum; i++) {
photoDiv = window.document.createElement("div");
// ----------------------------------------------------两句代码都是设置class属性值
photoDiv.setAttribute("class", "photo");
// photoDiv.className = "photo";
// ----------------------------------------------------两句代码都是设置id属性值
photoDiv.setAttribute("id", i+1+"");
// photoDiv.id=i+1+"";
// ----------------------------------------------------
photoDiv.style.backgroundImage = "url('image/" + (i + 1) + ".jpg')"
body.appendChild(photoDiv);
}
// 最顶层置上一层薄纱
let veilDiv=window.document.createElement("div");
veilDiv.setAttribute("class","veil");
// veilDiv.className=veil";
body.append(veilDiv);
}
let index = 0;
let photos = window.document.getElementsByClassName("photo");
function turn()//轮播图
{
if (index==photos.length)
{
index = 0;
}
for (let i = 0; i < photos.length; i++) {
photos[i].style.display = "none";
}
photos[index].style.display = "block";
index++;
}
generateElement();
setInterval(turn, 2000);//每隔两秒调用一次轮播图函数
CSS
body
{
margin: 0;
padding: 0;
background-color: #FDE6E0;
}
.photo
{
width: 100%;
height: 100%;
/*background-image: url("image/1.jpg");*/
background-size:cover;
background-repeat: no-repeat;
position: absolute;
}
.veil
{
width: 100%;
height: 100%;
background-color: #E9EBFE;
opacity:0.3;
position: absolute;
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>turnPhoto1</title>
</head>
<body id="body">
</body>
</html>
玩JavaScript的感受
代码不难,粗心就会出错!