jquery 实现moblie h5中图片随意拖拽

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="author" content="">
    <meta name="copyright" content="">
    <meta name="keywords" content="">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta content="telephone=no" name="format-detection">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="referrer" content="never" charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>拖拽</title>

    <!-- <link rel="stylesheet" href="./css/root.css">
    <link rel="stylesheet" href="./css/layout.css"> -->
</head>
<style>
    .icon {
        position: fixed;
        right: 0;
        bottom: 10%;
        z-index: 2;
        width: 100px;
        height: 100px;
        background: url(images/floatImg.png);
    }
</style>

<body>
    <div class="icon"></div>
</body>

<script src="./js/jq2.0.0.min.js"></script>//引用jquery min 的js文件即可
<script>

    $(function () {
        $('.icon').on('touchstart', function (e) {
            e.preventDefault();
        })
        $('.icon').on('touchmove', function (e) {
            e.preventDefault();
            var dw = $('.icon').width(), dh = $('.icon').height();
            var startX = e.originalEvent.changedTouches[0].pageX;

            var startY = e.originalEvent.changedTouches[0].pageY;

            // var moveEndX = e.originalEvent.changedTouches[0].pageX;

            // var moveEndY = e.originalEvent.changedTouches[0].pageY;

            console.log(dw, dh)
            $(this).css({
                top: startY - dh / 2,
                left: startX - dw / 2,
            })
            // console.log(startX, startY, moveEndX, moveEndY)
        })
        $('.icon').on('touchend', function (e) {
            e.preventDefault();
        })
    })
</script>

</html>

 

jquery 实现moblie h5中图片随意拖拽

项目中效果图如上,可随意推拽至任何位置

 

上一篇:vue文件拖动上传


下一篇:preventDefault() 方法 取消事件的默认动作