需求:
向右滑动按钮,按钮移动至可滑动间距的一半距离或全部,则界面跳转至解锁后的页面。
解析:
1,初始界面为手机锁屏界面,下方为了向右的箭头按钮
2,按住按钮向右滑动,如滑动距离不过半,松开鼠标后按钮向左返回初始位置,如距离过半或全部,则界面跳转至解锁页面。
3,原作中,直接操作dom,更改最外层div元素的background。
4,现在改为根据按钮的移动距离,来给外层div元素添加/移除 class,达到同样的效果。
5,依然需要对底层元素进行操作,改为用指令可能会更合适(有时间再尝试)
<template>
<div id="app">
<div id="iphone" :class="{base:isBase,new:isNew}">
<div id="lock" ref="lock">
<span ref="btn" v-show="isShow" @mousedown="handleDown"></span>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
isBase:true,
isNew:false,
isShow:true,
}
},
methods:{
handleDown(e){
var _this = this;
var lock=this.$refs.lock;
var btn = this.$refs.btn;
var maxL = lock.clientWidth - btn.offsetWidth;
var disX = e.clientX - btn.offsetLeft;
document.onmousemove=function(e){
var l = e.clientX - disX;
l < 0 && (l = 0);
l > maxL && (l = maxL);
btn.style.left = l + 'px';
btn.offsetLeft == maxL && (_this.isBase=false,_this.isNew=true,_this.isShow=false);
return false;
};
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
btn.releaseCapture && btn.releaseCapture();
btn.offsetLeft > maxL / 2 ?
_this.startMove(btn,maxL, function(){
_this.isBase=false;
_this.isNew=true;
_this.isShow=false
}) :
_this.startMove(btn,0)
};
this.setCapture && this.setCapture();
return false;
},
startMove(btn,target,callback){
var _this=this;
clearInterval(btn.timer);
btn.timer=setInterval(function(){
_this.doMove(btn,target,callback);
},30)
},
doMove(btn,target,callback){
var iSpeed = (target - btn.offsetLeft) / 5;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
target == btn.offsetLeft ? (clearInterval(btn.timer),callback && callback()) : btn.style.left = iSpeed + btn.offsetLeft + 'px';
}
}
}
</script>
<style>
#iphone{
position: relative;
426px;
height: 640px;
margin: 10px auto;
}
.base{
background: url(./assets/lesson8/iphone/1.jpg) no-repeat;
}
.new{
background: url(./assets/lesson8/iphone/-2.jpg) no-repeat;
}
#lock{
position: absolute;
left: 50%;
bottom: 33px;
358px;
height: 62px;
margin-left: -179px;
}
#lock span{
position: absolute ;
93px;
height: 62px;
cursor: pointer;
background: url(./assets/lesson8/iphone/btn.jpg) no-repeat;
}
</style>