本文直说布局,不提动画效果的实现。
移动端轮播图往往要做到自适应屏幕,一般布局如下:
html
一般侧滑无缝式轮播图都是如此布局,3张轮播的要准备3+2张图,每个item外套一层有个特别大的width,外面再套一层有在屏幕范围内的固定宽度,设置overflow:hidden。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no"> <title>test</title> <link rel="stylesheet" type="text/css" href="./index.css"> </head> <body> <div>移动端常见的根据可视区宽度自适应的轮播图布局。</div><br/> <div class="slider"> <div class="slider-group"> <div class="slider-item"> <a href="javascript:;"> <img src="./3.jpg"> </a> </div> <div class="slider-item"> <a href="javascript:;"> <img src="./1.jpg"> </a> </div> <div class="slider-item"> <a href="javascript:;"> <img src="./2.jpg"> </a> </div> <div class="slider-item"> <a href="javascript:;"> <img src="./3.jpg"> </a> </div> <div class="slider-item"> <a href="javascript:;"> <img src="./1.jpg"> </a> </div> </div> <div class="dots"> <span class="dot active"></span> <span class="dot"></span> <span class="dot"></span> </div> </div> </body> <script type="text/javascript" src="./index.js"></script> <script type="text/javascript"> window.onload = function() { setSliderWidth(); } </script> </html>
css
重点是img设置width:100% ,这样图片就能随外层宽度等比缩放。
/*min-height: 1px 是为了防止文本的溢出*/
.slider {
position: relative;
overflow: hidden;
min-height: 1px;
}
.slider-groups {
position: relative;
overflow: hidden;
white-space: nowrap;
}
.slider-item {
float: left;
box-sizing: border-box;
overflow: hidden;
text-align: center;
}
.slider-item a {
display: block;
100%;
overflow: hidden;
text-decoration: none;
}
.slider-item img {
display: block;
100%;
}
/* right: 0;left: 0; 是为了使width为100%,
有了宽度text-align才能生效,当然你直接写100%也行*/
.dots {
position: absolute;
right: 0;
left: 0;
bottom: 12px;
text-align: center;
font-size: 0;
}
.dot {
display: inline-block;
margin: 0 4px;
8px;
height: 8px;
border-radius: 50%;
background: green;
}
.active {
20px;
border-radius: 5px;
background: rgb(255, 205, 49);
}
js
这是重点。在每次页面初始化时设定特别大width具体的值
function setSliderWidth() { const p = document.getElementsByClassName('slider')[0]; const c = document.getElementsByClassName('slider-group')[0]; const ifLoop = true; let children = c.children; let width = 0;
//注意三个xxWidth值的区别,clientWidth包含了页面右侧滑轨的宽度 // let sliderWidth = p.clientWidth; // let sliderWidth = p.offsetWidth; let sliderWidth = window.innerWidth; for(let i=0;i<children.length;i++) { let child = children[i]; child.style.width = sliderWidth + 'px'; width += sliderWidth; }; if(ifLoop) { width += 2 * sliderWidth; }; c.style.width = width + 'px'; }
总结:越灵活的布局越需要js的支撑。
本节完,若有看客,望不吝拍砖。