1,首先需要div布局一个HTML框架出来:
2.在HTML里面的布局的截图如下:
2.添加CSS样式代码:
css代码:.jd_banner {
width: 100%;
position: relative;
overflow: hidden;
}
.jd_banner ul:nth-child(1) {
width: 1000%;
-webkit-transform: translateX(-10%);
transform: translateX(-10%);
}
.jd_banner ul:nth-child(1) li {
width: 10%;
float: left;
}
.jd_banner ul:nth-child(1) li a {
display: block;
width: 100%;
}
.jd_banner ul:nth-child(1) li a img {
width: 100%;
display: block;/* 清除img之间的间距 */
}
.jd_banner ul:nth-child(2) {
position: absolute;
width: 118px;
height: 6px;
left: 50%;
margin-left: -59px;
bottom: 5px;
}
.jd_banner ul:nth-child(2) li {
float: left;
width: 6px;
height: 6px;
border: 1px solid #fff;
border-radius: 50%;
margin-left: 10px;
}
.jd_banner ul:nth-child(2) li.now {
background: #fff;
}
.jd_banner ul:nth-child(2) li:first-child {
margin-left: 0;
}
3.CSS样式的代码截图如下:
3.主要是要写好javascript代码:
function banner () {
var banner = document.querySelector('.jd_banner');
var width = banner.offsetWidth;
var imgBox = banner.querySelector('ul:first-child');
var pointBox = banner.querySelector('ul:last-child');
var points = pointBox.querySelectorAll('li');
var addTransition = function () {
imgBox.style.webkitTransition = 'all .2s';
imgBox.style.transition = 'all .2s';
}
var removeTransition = function () {
imgBox.style.webkitTransition = 'none';
imgBox.style.transition = 'none';
}
var setTranslateX = function (x) {
imgBox.style.webkitTransform = 'translateX('+x+'px)';
imgBox.style.transform = 'translateX('+x+'px)';
}
var index = 1;
var timer = setInterval(function () {
index++;
addTransition();
setTranslateX(-index*width);
},3000);
var setPoint = function () {
for(var i = 0; i < points.length; i++) {
points[i].className = '';
points[index - 1].className = 'now';
}
};
transition.transitionEnd(imgBox, function () {
if(index >= 9) {
index = 1;
removeTransition();
setTranslateX(-index*width);
} else if(index <= 0) {
index = 8;
removeTransition();
setTranslateX(-index*width);
}
setPoint();
});
var startX = 0;
var moveX = 0;
var distanceX = 0;
var isMove = false;
imgBox.addEventListener('touchstart', function (e) {
clearInterval(timer);
startX = e.touches[0].clientX;
});
imgBox.addEventListener('touchmove', function (e) {
isMove = true;
moveX = e.touches[0].clientX;
distanceX = moveX - startX;
removeTransition();
setTranslateX(-index*width+distanceX);
});
window.addEventListener('touchend', function (e) {
if(Math.abs(distanceX) > (width/3) && isMove) {
if(distanceX > 0) {
index--;
} else {
index++;
}
addTransition();
setTranslateX(-index*width);
} else {
addTransition();
setTranslateX(-index*width);
}
startX = 0;
moveX = 0;
distanceX = 0;
isMove = false;
clearInterval(timer);
timer = setInterval(function () {
index++;
addTransition();
setTranslateX(-index*width);
},3000);
});
}
javascript代码截图如下:
6.最终在页面的效果如下:
图片不重要,你可以换一下你需要的图片进去