轮播器算是前端er喜欢做的一个小demo,我也被师兄说过能不能随手写一个轮播出来,然后乘着项目可能需要一个高度自定义的轮播图,我就自己看了一下网上的说明,然后自己捣鼓了一个最简单的,只是一种思路!!
思路
一般是定义一个可视窗口作为轮播主体,然后在定义一个轮播内容,这个内容是轮播主体宽度的n倍
开工
HTML
<div class="carousel_warp">
<div class="carousel_item" style="left:-600px">
<div>4</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>1</div>
</div>
<a href="javascript:;" id="prev" class="arrow"><</a>
<a href="javascript:;" id="next" class="arrow">></a>
</div>
其中carousel_warp就是轮播主体,然后carousel_item是轮播内容块
CSS
body{
padding:20px 50px;
}
.carousel_warp{
position: relative;
width: 600px;
height: 400px;
border: 1px solid #333;
overflow: hidden;
/* 这里是很重要的 */
}
.carousel_item{
width:3600px;
height: 400px;
position: absolute;
top: 0;
transition: left .2s ease-in;
}
.carousel_item>div{
float:left;
width:600px;
height:400px;
}
.arrow {
position: absolute;
top: 180px;
z-index: 2;
display: block;
width: 40px;
height: 40px;
font-size: 24px;
line-height: 39px;
text-align: center;
color: #fff;
background-color: RGBA(0, 0, 0, .3);
cursor: pointer;
}
.arrow:hover {
background-color: RGBA(0, 0, 0, .7);
}
#prev {
left: 20px;
}
#next {
right: 20px;
}
CSS这块随便看看就行了
Javascript
const prev = document.querySelector('#prev');
const next = document.querySelector('#next');
var carouselItem = document.querySelector('.carousel_item')
window.onload = function() {
function animate(offset) {
//说明一下style.left只能获取写在内联样式中的值,写在<style></style>中的是获取不到的 具体获取百度
//获取的是style.left,是相对左边获取距离,所以第一张图后style.left都为负值,
//且style.left获取的是字符串,需要用parseInt()取整转化为数字。
var newLeft = parseInt(carouselItem.style.left) + offset;
console.log(newLeft);
if(newLeft < -2400) {
carouselItem.style.left = -600 + 'px';
} else if(newLeft > -600) {
// carouselItem.style.transition = 'none';
carouselItem.style.left = -2400 + 'px';
} else {
carouselItem.style.transition = 'left .2s ease-in';
carouselItem.style.left = newLeft + 'px';
}
}
prev.onclick = function() {
animate(600);
}
next.onclick = function() {
animate(-600);
}
}
到这里算是一个小ok状态了
到这里大家看到效果了,觉得是不是感觉有点视觉上的问题呢,就是1切换到4的时候和4切换到1的时候会有回退现象。
而且到这里也要思考为什么在布局的时候在最上方和最下面会有copy1和copy4的存在,这两个就是为下面视觉处理做贡献的。
我也是看别人写的怎么处理,简单的讲就是利用setTimeout()函数来做到copy1和copy4的时候回退1和4
if(newLeft < -2400) {
carouselItem.style.left = newLeft + 'px';
//就是这里 到最后一个4的时候再去copy1 然后setTimeout()重定位left,
setTimeout(function(){
carouselItem.style.transition = 'none';
carouselItem.style.left = -600 + 'px';
},200)
} else if(newLeft > -600) {
// carouselItem.style.transition = 'none';
carouselItem.style.left = newLeft + 'px';
//同理上方也是重定位
setTimeout(function(){
carouselItem.style.transition = 'none';
carouselItem.style.left = -2400 + 'px';
},200)
} else {
carouselItem.style.transition = 'left .2s ease-in';
carouselItem.style.left = newLeft + 'px';
}
正餐来了
哈哈哈,是不是感觉很简单了呢!!
下面其实还应该做锚点跳转的,但是我觉得大家可以自己动手试试,只不过做锚点了的话就不能切换用具体数值了,肯定需要建一个对象来存取一些自定义数值,比如主体宽度,总宽度,然后写切换函数也不能是死数据,应该是index*width这种了!!