前端学习之路之图片轮播
近期学习了不少的前端知识和前端的一些应用,今天呢就实现了一下图片的轮播效果,话不多说。
图片轮播的本质就是类似走马灯,当用户点击指示器的时候,需要轮播的图片发生偏移就行了。
使用setInterval实现自动轮播.
首先呢就是创建div包裹所有的内容,下面有两个板块,一个呢就是图片移动的板块,另一个就是指示器的板块
<div class="container">
<ul class="carousel">
<li><img src="../images/pic.png" alt=""></li>
<li><img src="../images/pic2.png" alt=""></li>
<li><img src="../images/pic3.png" alt=""></li>
<li><img src="../images/pic4.png" alt=""></li>
</ul>
<div class="container_footer">
<span class="active"></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
两个板块就创建完成了,接下来呢就是实现CSS样式.在图片的板块中使用flex弹性布局,将图片横向放置,并且将图片的大小设置一下
.carousel{
width: 100%;
height: 100%;
display: flex;
transition: 1s; /*设置css属性的变化时间*/
transform: rotateX(0);
}
/* 改变设置图片的尺寸 */
.container>ul img{
width: 300px;
height: 200px;
}
然后呢就是实现指示器的样式设置
.container_footer{
position: absolute;
bottom: 10px;
display: flex;
/* outline: 1px solid #fff; 加上边框 */
left: 50%; /*位置*/
transform: translateX(-50%);/*移动50%*/
}
.container_footer span{
width: 20px;
height: 20px;
border: 2px solid white; /*边框设置*/
border-radius: 50px;
margin: 0 3px;
}
.container_footer span:hover{
cursor:pointer;
}
.container_footer span.active{
background-color: #fff;
border-color: rgb(225, 44, 44);
}
样式设置完毕之后呢即是JS的设置,通过个指示器设置点击事件,来获取需要的信息进行移动
// 定义对象获取需要的dom元素
var doms = {
carousel:document.querySelector('.carousel'),//轮播区域
indicators:document.querySelectorAll('.container_footer span'),
};
// 创建函数表示当前板块显示的图片
function moveTo(index){
doms.carousel.style.transform= `translateX(-${index}00%)`;
// 去除当前选中的指示器
var active = document.querySelector('.active');
// active.className = '';
active.classList.remove('active');
// 重新选择指示器
// doms.indicators[index].className='active';
doms.indicators[index].classList.add('active');
}
// 给每个span添加onclick事件
doms.indicators.forEach(function(item,i){
item.onclick = function(){
moveTo(i);
};
})
这样就能实现图片轮播了,当然还可以实现根据时间的增加试下图片的轮播.
自动轮播板块
function moveLeft(){
var active = document.querySelector('.active');
active.classList.remove('active');
x = findindes(active)
if(active.nextElementSibling == null){
doms.indicators[0].classList.add('active');
moveTo(0)
}
else{
active.nextElementSibling.classList.add('active');
moveTo(x+1)
};
}
function autoRun(){
return setInterval(moveLeft,1000);
}
var timer = autoRun(); //调用定时器
实现鼠标放上去后停下轮播
doms.carousel.onmouseover = function() {
clearInterval(timer)
}
doms.carousel.onmouseout = function(event) {
timer = setInterval(moveLeft, 1000)
}