效果展示
SDGIF_Rusult_1.gif
程序设计思路
利用c3的变换,以及触摸事件进行设计
HTML框架
JavaScript部分
var ul = document.querySelector('ul');
var focus = document.querySelector('.focus');
var index = 0;
var w = focus.offsetWidth;
var ol = document.querySelector('ol');
var time = setInterval(function() {
index++;
// console.log(index);
var translatex = -index * w;
// console.log(translatex);
ul.style.transition = 'all .3s';
ul.style.transform = 'translateX(' + translatex + 'px)';
}, 2000);
//判断滑动出界怎么办
ul.addEventListener('transitionend', function() {
if (index >= 3) {
index = 0;
ul.style.transition = 'none';
var translatex = -index * w;
ul.style.transform = 'translateX(' + translatex + 'px)';
} else if (index < 0) {
index = 2;
ul.style.transition = 'none';
var translatex = -index * w;
ul.style.transform = 'translateX(' + translatex + 'px)';
}
//清除带有current类的li
ol.querySelector('.current').classList.remove('current');
//为当前的小li添加current类
ol.children[index].classList.add('current');
});
//触摸效果
var startX = 0;
var moveX = 0;
ul.addEventListener('touchstart', function(e) {
startX = e.targetTouches[0].pageX;
clearInterval(time);
// console.log(startX);
})
ul.addEventListener('touchmove', function(e) {
moveX = e.targetTouches[0].pageX - startX;
var translatex = -index * w + moveX;
ul.style.transform = 'translateX(' + translatex + 'px)';
})
ul.addEventListener('touchend', function(e) {
clearInterval(time);
time = setInterval(function() {
index++;
var translatex = -index * w;
ul.style.transition = 'all .3s';
ul.style.transform = 'translateX(' + translatex + 'px)';
}, 2000);
//回弹效果
if (Math.abs(moveX) >= 50) {
if (moveX > 0) {
index--;
var translatex = -index * w;
ul.style.transition = 'all .3s';
ul.style.transform = 'translateX(' + translatex + 'px)';
} else {
index++;
var translatex = -index * w;
ul.style.transition = 'all .3s';
ul.style.transform = 'translateX(' + translatex + 'px)';
}
} else {
var translatex = -index * w;
ul.style.transition = 'all .3s';
ul.style.transform = 'translateX(' + translatex + 'px)';
}
})
css部分
* {
margin: 0;
padding: 0;
}
.focus {
/* border: 1px solid red; */
position: relative;
width: 375px;
overflow: hidden;
}
ul {
width: 500%;
padding-left: 0;
overflow: hidden;
}
ul li {
float: left;
width: 20%;
list-style: none;
}
ul li img {
width: 100%;
}
ol {
position: absolute;
right: 10px;
bottom: 10px;
}
ol li {
float: left;
width: 5px;
height: 5px;
margin-right: 10px;
list-style: none;
transition: all .2s;
background-color: #ffffff;
}
.current {
width: 10px;
}