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

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;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值