干货如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>图片轮播</title>
<link rel="stylesheet" href="../css/homew.css">
<link rel="stylesheet" href="../font_7zx7sik14qk/iconfont.css">
</head>
<body>
<section>
<div class="backHole">
</div>
<div id="mid">
<div class="rowleft iconfont icon-jiantouxia" onclick="leftRow()">
</div>
<div class="rowright iconfont icon-jiantouxia" onclick="rightRow()">
</div>
<div id="imgs">
<img src="../images/1.jpg" alt="">
<img src="../images/2.jpg" alt="">
<img src="../images/3.jpg" alt="">
<img src="../images/4.jpg" alt="">
<img src="../images/5.jpg" alt="">
<img src="../images/6.jpg" alt="">
<img src="../images/7.jpg" alt="">
<img src="../images/8.jpg" alt="">
</div>
</div>
<div class="bott">
</div>
</section>
<script src="../JavaScript/homew.js"></script>
</body>
</html>
Css样式设置如下
body{
margin: 0;
background-image: url("../images/background.jpg");
}
.backHole{
font-size: 0;
height: 70px;
width: 1000px;
/* background-color: white; */
background-image: url("../images/topbg.png");
/* background-repeat: inherit; */
}
section{
width: 1000px;
height: 400px;
margin: auto;
margin-top: 100px;
}
#mid{
height: 400px;
width: 1000px;
position: relative;
overflow: hidden;
}
.bott{
width: 1000px;
height: 50px;
background-image: url("../images/bottombg.png");
font-size: 0;
}
div.iconfont{
width: 40px;
height: 40px;
font-size: 36px;
background-color: #72727298;
text-align: center;
line-height: 40px;
cursor: pointer;
}
.rowleft{
position: absolute;
left: 0;
top: 180px;
z-index: 10;
transform: rotate(90deg);
}
.rowright{
position: absolute;
right: 0;
top: 180px;
z-index: 10;
transform: rotate(-90deg);
}
div#imgs>img{
width: 1000px;
height: 400px;
position: absolute;
transition: all 1s linear;
}
#imgs>img:first-child{
/* 将第一张放在有效区域的右边 */
left: 1000px;
}
#imgs>img:nth-child(2){
/*一定要对中间图片设置定位,不然没有过渡效果*/
left: 0;
}
#imgs>img:nth-child(2)~img{
/* 将剩余图片放在有效区域的左边 */
left: -1000px;
}
JS代码如下:
var imgs = document.getElementsByTagName("img");
var imgDiv = document.getElementById("imgs");
console.log(imgs)
function rightRow(){
//appendChild会将第一个图片重新抽出并添加到最后
imgDiv.appendChild(imgs[0])
}
function leftRow(){
//prepend会将最后一张图片重新抽出并放到最前面
imgDiv.prepend(imgs[7])
}
最重要的是CSS的样式设置,第一张放在有效区域右边,才能在第一张被抽出的时候,第二张图片移动到第一张的位置,也就是往右移出可视区域;往左只需要把第三张之后的图片全部叠在可视区域的左边,点击左移箭头,最后一张图片被抽出移动到第一张的位置,之前的第一张则会向左移入到可视区域。
没有过渡效果的可能问题:
- transition属性要设置在所有的img身上,因为是img被抽离;
- 第二张图片的定位 ”left:0; ”是必要的;
- img的所有定位属性方向需要统一,都为left或都为right;