好代码要存起来:
DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>适配移动端的拖动效果title>
<style>
#div1{
height: 1000px;
}
#div2{
position: absolute;
top:0;
left:0;
width: 100px;
height: 100px;
background: #bbbbbb;
}
style>
head>
<body>
<div id="div1">
<div id="div2">div>
div>
<script>
var flag = false;
var cur = {
x:0,
y:0
}
var nx,ny,dx,dy,x,y ;
function down(){
flag = true;
var touch ;
if(event.touches){
touch = event.touches[0];
}else {
touch = event;
}
cur.x = touch.clientX;
cur.y = touch.clientY;
dx = div2.offsetLeft;
dy = div2.offsetTop;
}
function move(){
if(flag){
var touch ;
if(event.touches){
touch = event.touches[0];
}else {
touch = event;
}
nx = touch.clientX - cur.x;
ny = touch.clientY - cur.y;
x = dx+nx;
y = dy+ny;
div2.style.left = x+"px";
div2.style.top = y +"px";
//阻止页面的滑动默认事件
document.addEventListener("touchmove",function(){
event.preventDefault();
},false);
}
}
var div2 = document.getElementById("div2");
div2.addEventListener("mousedown",function(){
down();
},false);
div2.addEventListener("touchstart",function(){
down();
},false)
div2.addEventListener("mousemove",function(){
move();
},false);
div2.addEventListener("touchmove",function(){
move();
},false)
document.body.addEventListener("mouseup",function(){
flag = false;
},false);
div2.addEventListener("touchend",function(){
flag = false;
},false)
script>
body>
html>
简单易用,就是这么任性。。。
ps:原文链接:http://blog.csdn.net/u014346301/article/details/53536714