仿蘋果返回首頁按鈕(移動端div拖動 返回首頁)

參考了網上的文章,然后又完善了一下

大概思路:

1、實現頁面的拖動效果:首先是明白移動端的touchstart touchmove touchend的用法

2、div移動其實就是它的left 和 top 的移動

3、touchstart 的時候,記錄鼠標的坐標和div的偏移量,由此可以計算出鼠標和div左側和頂部的距離

4、touchmove 的時候,記錄新的鼠標坐標,用新的坐標-起點鼠標和偏移量的差值=div需要移動的距離

5、邊界值限制,防止div 移出來

6、禁止底層滑動

7、跳轉到首頁或者百度


我的w3cfuns 同篇文章http://www.qdfuns.com/notes/19055/1b91973818e1014978641524cbe3f215.html

dragFn('div1','http://www.baidu.com');

function dragFn(id,path){

var dom = document.getElementById(id);

var flag = false;

var cur = {

x:0,

y:0

}

var skip = 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 = dom.offsetLeft; // 當前元素距離外層元素的位置

dy = dom.offsetTop;

}

function move(){

event.preventDefault();//阻止觸摸時瀏覽器的縮放、滾動條滾動等

if(flag){

skip = 1;

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;

if(x < 0){

x = 0

}else if(x > document.documentElement.clientWidth - dom.offsetWidth){

x = document.documentElement.clientWidth - dom.offsetWidth

}

if(y < 0){

y = 0

}else if(y > document.documentElement.clientHeight - dom.offsetHeight){

y = document.documentElement.clientHeight - dom.offsetHeight

}

dom.style.left = x +'px';

dom.style.top = y +'px';

return;

}

}

// 鼠標釋放時候的函數

function end(){

flag = false;

move();

if(skip == 0){ // 判斷是否出發了touchmove

location.href = path;

}

}

dom.addEventListener('touchstart',function(){

skip = 0;

down();

},false)

dom.addEventListener('touchmove',function(){

move();

},false)

dom.addEventListener('touchend',function(){

end();

},false)

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容