寫這個麼個題目好像,有點晦澀。直接來張gif圖就知道,主要是是當手指觸摸到元素時,元素的初始位置變成了left:0, top:0;
js 設置監聽事件 都是 一樣的套路
touch.addEventListener('touchstart', function(evtend) {}, false);
touch.addEventListener('touchmove', function(evtend) {}, false);
touch.addEventListener('touchend', function(evtend) {}, false);
var endpst = {}, //結束位置
elepst= {},
start={}; //初始位置
item.addEventListener('touchstart', function(event) {
if(event.targetTouches.length > 1) return;
var offset, touch = event.targetTouches[0],
style = window.getComputedStyle(this, null);// 當前元素的css 樣式
start = {x: touch.clientX, y: touch.clientY};
elepst = {
x: parseFloat(style.getPropertyValue('left')),
y: parseFloat(style.getPropertyValue('top')),
};
}, false);
item.addEventListener('touchmove', function(event) {
if(event.targetTouches.length > 1) return;
var touch = evtmv.targetTouches[0],
offset = { x : touch.clientX - start.x, y : touch.clientY - start.y }; //手移動的 偏移位置
endpst['left'] = elepst.x + offset.x;
endpst['top'] = .y + offset.y;
this.style.left = endpst.left+ 'px';
this.style.top = endpst.top + 'px';
}, false);
//移動結束
item.addEventListener('touchend', function(e) {
if(e.targetTouches.length > 1) return;
}, false);
這樣寫在安卓和電腦上是沒問題的, 但到了水果上狀況如上圖,操作後,在第一次移動時,位置變成0,再次操作位置就是和手機的運動是一樣的。
分析,初始化頁面時,position,是讀取css文件渲染的況且是百分比定位。第二次移動時,position在元素屬性上
由此 最直接辦法就是 給每個需要移動的 元素 用js 設置位置。
var ary = document.querySelectorAll(eles)
for (var k = start , itm; itm = ary[k++];) {
var left = itm.getBoundingClientRect().left,
top = itm.getBoundingClientRect().top;
itm.style.cssText = 'top:' + top + 'px;left:' + left +'px';
}
如此 當在水果上第一次觸摸拖動元素時 ,位置就不會爲0。
getBoundingClientRect有個尷尬的地方就是,eles 元素和父類元素 即所在分頁吧,必須可見,纔有值否則爲0;
有需要的交流的可以加個好友