最近被分到了手机端做任务,需求是在原页面上加上tab滑动切换,由于之前没有做过手机端的任务心里还是有点慌慌的,于是提前先去度了一下相关的知识点,然后自己整理了一下,以备以后再次用到。
- 通过事件touchstart和touchend来判断左滑还是右滑
<div style="width: 100%;height: 3000px;background: #aaa;" id="main">
内容区域
</div>
<script>
(function(){
var startx;
var endx;
var el = document.getElementById('main');//触摸区域。
function judge() {
console.log(startx,endx);
if (startx > endx) { //判断左右移动程序
console.log("left");
} else {
console.log("right");
}
}
el.addEventListener('touchstart', function (e) {
var touch = e.changedTouches;
startx = touch[0].clientX;
starty = touch[0].clientY;
});
el.addEventListener('touchend', function (e) {
var touch = e.changedTouches;
endx = touch[0].clientX;
endy = touch[0].clientY;
judge();
});
})();
</script>
这块主要是通过手指点击时获取手指触摸屏幕和离开屏幕时接触点距屏幕左边的距离来判断,同样也可以通过starty和endy的值来判断手指是向下滑动还是向上滑动
- 通过css实现页面内的滑动效果
仅通过css的属性实现移动端手机屏幕上的滑动效果,具体实现的代码如下:
<style type="text/css">
.slide-box{
margin-top: 200px;
display: -webkit-box;
-webkit-overflow-scrolling:touch;
overflow: auto;
}
.slide-item{
width: 200px;
height: 200px;
border:1px solid #000;
margin-right: 30px;
}
::-webkit-scrollbar{
display: none;
}
</style>
<div class="slide-box">
<div class="slide-item">item1</div>
<div class="slide-item">item2</div>
<div class="slide-item">item3</div>
<div class="slide-item">item4</div>
<div class="slide-item">item5</div>
</div>
首先需要一个父容器,这块不用去设置父容器的宽度就默认展示的宽度是屏幕的宽度,重要的css属性就是display: -webkit-box;然后在每个子容器中设置需要展示的子容器的大小样式,注会的属性
::-webkit-scrollbar{
display: none;
}
是为了实现手机端滑动时出现的滚动条,同样你也可以不去设置这个属性,只是在滑动的时候会展示一个滑动条,这个就视情况而定了。