undefinedfix
Sign in

When the mobile end drags the element, the element is displaced

VirgileD edited in Tue, 19 Apr 2022

Originally, I did a small example of image dragging, but I found that the image would be dislocated and offset at the moment when my finger touched it and started to move, but I could still drag it at the back;

HTML code:

<body>
    <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1541232625&di=e713ce2bf4b01d5484e31810ed0c97c0&imgtype=jpg&er=1&src=http%3A%2F%2Ftx.haiqq.com%2Fuploads%2Fallimg%2F150327%2F211551I17-12.jpg" style="width:100px;" class="small-pic">
    <div class="mask">
        <img src="" alt="" class="big-pic" style="max-width: 100%;">
    </div>
</body>

CSS part

.mask{
    position: fixed;
    width:100vw;
    height:100vh;
    background-color:rgba(0,0,0,.8);
    top: 0;
    left: 0;
    display: none;
}
.big-pic{
    position: absolute;
    top: 50%;
    left:50%;
    transform:translate(-50%,-50%);
}

JS part

<script type="text/javascript">
    function dropImg(obj){
        $(obj).on('touchstart',function(event){
            var disx=event.originalEvent.changedTouches[0].clientX-$(obj).offset().left;
            var disy=event.originalEvent.changedTouches[0].clientY-$(obj).offset().top;
            var moveFlag=true;
            $(document).on('touchmove',function(event){
                event.preventDefault();
                if(moveFlag){
                    $(obj).css({
                        "left":event.originalEvent.changedTouches[0].clientX - disx,
                        "top":event.originalEvent.changedTouches[0].clientY - disy
                    });
                }
            });
            $(document).on('touchend',function(){
                moveFlag=false;
            })
        });
    }
    $(document).ready(function() {
        $('.small-pic').on('touchstart',function(){
            var tag=$(this).attr('src');
            $('.big-pic').attr('src',tag);
            $('.mask').show();
            var oImg=$('.big-pic')
            dropImg(oImg);
        })
    });
</script>
1 Replies
kcomf
commented on Tue, 19 Apr 2022
 $(obj).css({
                        "left":event.originalEvent.changedTouches[0].clientX - disx,
                        "top":event.originalEvent.changedTouches[0].clientY - disy
                    });

After setting up here, transform:translate (- 50%, - 50%); attributes make the picture deviate

lock This question has been locked and the reply function has been disabled.