您的位置:首页 > Web前端 > JavaScript

hammer.js---拖动滑块实现验证的小demo

2016-09-19 18:52 369 查看
1.先看一下效果图

 移动端实现,简单方便,只要稍作修改比如用Math.random()函数生成一个随机的位置,然后判断位置差即可。

快去试一试这个很fashion的库吧。



2.看一下HTML结构

<div class="indicator-container">
<div class="indicator">
slider
</div>

<div class="trap">

</div>
</div>

<div class="handsome">
Oh!You are so handsome!
</div>


3.JS部分

function indicatorPan(){
var hammer=new Hammer($(".indicator").get(0));
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
var pos_x=$(".indicator").position().left;
var pos_y=$(".indicator").position().top;
console.log(pos_x);
console.log(pos_y);
hammer.on("pan",function(e){

// console.log(e);
// console.log(e.deltaX);
// console.log(e.deltaY);

$(".indicator").css("left",pos_x+e.deltaX);
$(".indicator").css("top",pos_y+e.deltaY);

});

var container_width=$(".indicator-container").width();
var container_height=$(".indicator-container").height();
hammer.on("panend",function(){
pos_x=$(".indicator").position().left;
pos_y=$(".indicator").position().top;
console.log(pos_x);
console.log(pos_y);
console.log("panend");
console.log(Math.abs(pos_x-container_width/2));
if(Math.abs(pos_x-container_width/2)<50 &&
Math.abs(pos_y-container_height/2)<50)
{
console.log("good");
$(".handsome").show();
}else{
$(".handsome").hide();
}
});
}

indicatorPan();

2017/8/24 号更新

css文件body{
font-family:"Helvetica","Microsoft Yahei";
padding:0;
margin:0;
}

.grid{
background-image:-webkit-linear-gradient(top,
transparent 49px,
#bfbebe 50px),
-webkit-linear-gradient(left,
transparent 49px,
#bfbebe 50px);

background-size:50px 50px;
background-repeat:repeat;
}

.description{
text-align:center;
}

.hammer{
width:200px;
height:100px;
background-color:grey;
margin:0 auto;
text-align:center;
line-height:100px;
}

.indicator-container{
position:relative;
width:100%;
height:300px;
border:1px solid black;
box-sizing:border-box;
}
.indicator{
position:absolute;
width:50px;
height:50px;
line-height:50px;
text-align:center;
background-color:#4CAF50;
color:white;
text-align:center;
z-index:2;

}

.trap{
position:absolute;
left:50%;
top:50%;
-webkit-transform:translate(-50%,-50%);
width:50px;
height:50px;
background-color:grey;
}

.handsome{
font-size:20px;
display:none;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: