关于iphone 上touch事件动态改变元素位置时与touch点发生偏移的问题

写这个么个题目好像,有点晦涩。直接来张gif图就知道,主要是是当手指触摸到元素时,元素的初始位置变成了left:0, top:0;



js 设置监听事件 都是 一样的套路 

touch.addEventListener('touchstart', function(evtend) {}, false);
touch.addEventListener('touchmove', function(evtend) {}, false);
touch.addEventListener('touchend', function(evtend) {}, false);


在事件里添加 进行位置的动态改变,首先就需要获得手指的初始位置,手指移动的位置,手机touch 当前元素的位置;

            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;




有需要的交流的可以加个好友


猜你喜欢

转载自blog.csdn.net/ling369523246/article/details/70227607