转载链接:http://www.lvtao.net/web/220.html
$(function(){
document.getElementById("moveId").addEventListener('touchstart', touchStart);
document.getElementById("moveId").addEventListener('touchmove', touchMove);
document.getElementById("moveId").addEventListener('touchend', function () {
isdrag = false;
});
});
在实现触屏中,我们必须采用js的addEventListener,接着加上 touchstart,touchmove,touchend。今天我们的代码里加上了jquery,只不过是用来获取ID及CSS,呵呵,毕竟,JQ大 家都在用。但对于事件的添加,大家还是得用document,getElementById这种模式,因为这东西只有JS才有,JQUERY里并没有 TOUCH这样的东西。
function touchStart(e) {
isdrag = true;
e.preventDefault();
tx = parseInt($("#moveId").css('left'));
ty = parseInt($("#moveId").css('top'));
x = e.touches[0].pageX;
y = e.touches[0].pageY;
}
大家可以看到,在代码里有这句话,e.preventDefault(),假设不写这一句,你在触屏的时候,页面就会滑动,所以它的作用是巨大的。。。
e.touches[0]表示什么呢?就是手势里的第一种,我们就认为是touch吧,触屏里还有其它两个手指的手势,我们今天就学一种,呵。。。
我们取得对像的left,top及手的触屏位置,这时,touchstart完成了。。。
function touchMove(e) {if (isdrag) {e.preventDefault();var n = tx + e.touches[0].pageX - x;var h = ty + e.touches[0].pageY - y;$("#moveId").css('left', n);$("#moveId").css('top', h);}
}
我们那个isdrag是用来判断是否可以拖动的,我们用手拖动后的位置加上对像的位置减去touchstart时的位置,就可以取得移动后的位置,这样,我们就完成了touchmove这个过程。。
对于touchend,我们就写上一个ifdrag=false,表示不再拖动啦。。。
演示代码
<!DOCTYPE>
<html>
<head>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="MobileOptimized" content="320"/>
<title>触屏特效,手机网页</title>
<style type="text/css">html{-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td,hr,button,article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section {margin:0;padding:0;}.dragme{background:#000;width:60px;height:60px; color:#fff; position:absolute; left:40px; top:40px; text-align:center; line-height:60px;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<div id="moveid" class="dragme"> lvtao.net
</div>
<script type="text/javascript">
var isdrag=false;
var tx,x,ty,y;
$(function(){ document.getElementById("moveid").addEventListener('touchstart',touchStart); document.getElementById("moveid").addEventListener('touchmove',touchMove);document.getElementById("moveid").addEventListener('touchend',function(){ isdrag = false; });
});
function touchStart(e){ isdrag = true; e.preventDefault();tx = parseInt($("#moveid").css('left')); ty = parseInt($("#moveid").css('top')); x = e.touches[0].pageX;y = e.touches[0].pageY;
}
function touchMove(e){ if (isdrag){e.preventDefault();var n = tx + e.touches[0].pageX - x;var h = ty + e.touches[0].pageY - y; $("#moveid").css("left",n); $("#moveid").css("top",h); }
}
</script>
</body>
</html>