RedSpite
移动端自适应banner轮播 手写
随着移动设备普及率越来越高,我们前端工程师现在必须掌握h5页面的书写了。 手机端展示方式不需要太复杂,毕竟屏幕只有这么大嘛不是,所以能搞得花样也不多,运用最多的就是轮播了吧!
我喜欢手写常用的前端功能,所以这次也试着自己摸索写一下吧~~
首先是需要了解的几位重要人物:
* touches
触摸点是有多个的,每个Touch对象包含的属性如下。
clientX:触摸目标在视口中的x坐标。
clientY:触摸目标在视口中的y坐标。
identifier:标识触摸的唯一ID。
pageX:触摸目标在页面中的x坐标。
pageY:触摸目标在页面中的y坐标。
screenX:触摸目标在屏幕中的x坐标。
screenY:触摸目标在屏幕中的y坐标。
target:触目的DOM节点目标。
* touchstart
touchstart 是手指触摸到屏幕一瞬间触发的事件,可以在这里记录手指在屏幕上的初始位置
var startX, startY, endX, endY;
$("#bannerm").on("touchstart",function(e){
//开始位置
startX = e.originalEvent.targetTouches[0].clientX;
});
* touchmove
touchmove 是手指在页面进行拖拽时触发的事件,可以在这里记录手指在屏幕的最后位置。 在这个事件发生期间,调用preventDefault()事件可以阻止滚动。
$("#mbanner").on("touchmove", function (e) {
e.preventDefault();
//结束位置
endX = e.originalEvent.targetTouches[0].clientX;
});
* touchend
touchend 是手指离开屏幕触发的事件,在这个事件发生期间,调用preventDefault()事件可以阻止滚动。
$("#mbanner").on("touchend", function (e) {
e.preventDefault();
if ((startX - endX) > 100) {
//判断滑动方向,初始 > 结束 向右
}
else if ((startX - endX) < -100){
//初始 < 结束 向左
}
});
现在来写一写轮播 (移动端查看)
1Html:
Css:
#mbanner{
width: 100%;
margin: 0 auto;
position: relative;
min-height: 100px;
overflow: hidden;
}
#mbanner ul{
width: 400%;
height: 100%;
}
#mbanner li{
position: relative;
width: 25%;
height: 0;
padding-bottom: 7.5%;
overflow: hidden;
float: left;
}
#mbanner li img{
width: 100%;
}
Js:
$(function () {
var startX, startY, endX, endY;
var size = $("#bannerm li").size();
$("#bannerm").on("touchstart",function(e){
startX = e.originalEvent.targetTouches[0].clientX;
clearInterval(t); //清除定时轮播
});
$("#bannerm").on("touchmove", function (e) {
e.preventDefault();
endX = e.originalEvent.targetTouches[0].clientX;
});
var i, _left;
var t = setInterval(move, 4000);
$("#bannerm").on("touchend", function (e) {
e.preventDefault();
if ((startX - endX) > 100) {
move()
}
else if ((startX - endX) < -100){
//初始 < 结束 左滑
i = $("#bannerm li.active").index();
i--;
if(i<0){
var lefts = -100*(size-1) +"%";
$("#bannerm ul").css("margin-left", lefts); //无缝轮播
i = size -2;
show()
}else {
show()
}
}
t = setInterval(move, 4000); //定时轮播启动
});
function move(){
//判断滑动方向,初始 > 结束 右滑
i = $("#bannerm li.active").index();
i++;
if(i == size){
$("#bannerm ul").css("margin-left", "0"); //无缝轮播
i = 1;
show();
}else{
show()
}
}
function show(){
_left = -100*i +"%";
$("#bannerm li").eq(i).addClass("active").siblings().removeClass("active");
$("#bannerm ul").animate({
"margin-left":_left
},500);
}
});
这样就完成了一个移动端自适应的轮播了,可滑动可自动轮播,而且是无缝的~ 我的代码可能还不够简洁,慢慢进步吧!
更新于2016.10.06
© RedSpite | 蜀ICP备16004270号