简单自动切换轮播图
2019-11-14 本文已影响0人
泽_0b48
<style type="text/css">
.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;*/
animation: switch 5s ease-out infinite;
}
.slider-item a {
display: block;
width: 100%;
overflow: hidden;
text-decoration: none;
}
.slider-item img {
display: block;
width: 100%;
}
/* right: 0;left: 0; 是为了使width为100%,
有了宽度text-align才能生效,当然你直接写width:100%也行*/
@keyframes switch {
0%,
45% {
margin-left: 0;
}
55%,
100% {
margin-left: -12.5%;
}
}
</style>
<div class="slider">
<div class="slider-group">
<div class="slider-item">
<a href="javascript:;">
<img src="/Public/assets/images/index/banner_1.jpg">
</a>
</div>
<div class="slider-item">
<a href="javascript:;">
<img src="/Public/assets/images/index/banner_2.jpg">
</a>
</div>
</div>
</div>
window.onload = function() {
setSliderWidth();
}
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';
}