轉載鏈接: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>