轮播图第一种方法:
简单型轮播图(HTML页面):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>turnPhoto1</title>
<link rel="stylesheet" href="css/turnPhoto1.css">
</head>
<body id="body">
</body>
<script src="js/turnPhoto1.js"></script>
</html>
整体调用的js内容部分:
let Maximum = 8;//photoDiv的最大个数,可灵活更改
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++) //所有的photoDiv不可见,for循环可以更改,但更改后却不一定能运行
{
photos[i].style.display = "none";
}
photos[index].style.display = "block";//让index所指向的photoDiv可见
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>turnPhoto2</title>
<link rel="stylesheet" href="css/turnPhoto2.css">
</head>
<body>
<img src="image/8.jpg" id="photo">
<script src="js/turnPhoto2.js"></script>
</body>
</html>
js调用内容部分(简单型):
let Maximum = 8;
let index = 1;
let photo =window.document.getElementById("photo");
function turn() {
if (index > Maximum) {
index = 1;
}
// ----------------------------------------------------------------设置img的src属性,两种写法任选
// photo.src = "image/" + index + ".jpg";
photo.setAttribute("src","image/"+index+".jpg");
// ----------------------------------------------------------------
index++;
}
setInterval(turn, 2000);
css样式部分:
body
{
padding: 0;
margin:0;
background-color: #C7EDCC;
}
#photo
{
width: 100%;
height: 100%;
position: absolute;
top:0px;
left:0px;
}