拖拽js

198 阅读1分钟

移动端拖拽

<style>
	.contents{
		width: 2.6rem;
        height: 2.6rem;
		box-sizing:border-box;
		position:fixed;
		top:0;
		left:auto;
		bottom:0;
	}
    .fixed_l{
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top:30%;
        z-index: 9999;
    }
</style>
	<body>
		<div class="contents">
			<div class="fixed_l" onclick="jumpType(4961,'jump')">
                <img class="pic" src="https://i1.douguo.com/upload/banner/2/d/a/2d603ee9316adbe0d8b66ec59ba6a86a.png" alt="">
            </div>
		</div>

// 需引用jq
<script type="text/javascript">
	$(function(){
		var contW = $(".fixed_l").width();
		var contH = $(".fixed_l").height();
		var startX, sX, moveX, moveY;
        var winW = $(".contents").width();
        var disY = 0;
		$(".fixed_l").on({ //绑定事件
			touchstart: function(e) {
				startX = e.originalEvent.targetTouches[0].pageX; //获取点击点的X坐标    
				sX = $(this).offset().left; //相对于当前窗口X轴的偏移量
				leftX = startX - sX; //鼠标所能移动的最左端是当前鼠标距div左边距的位置
				rightX = winW - contW + leftX; //鼠标所能移动的最右端是当前窗口距离减去鼠标距div最右端位置
                disY = e.originalEvent.targetTouches[0].clientY - this.offsetTop;
			},
			touchmove: function(e) {
				e.preventDefault();
				//移动过程中XY轴的坐标要减去margin的距离
				moveX = e.originalEvent.targetTouches[0].pageX; //移动过程中X轴的坐标
				//判断的时候要计算加上padding的距离
				if(moveX < leftX) {
					moveX = leftX;
				}
				if(moveX > rightX) {
					moveX = rightX;
				}
                var moveY = e.originalEvent.targetTouches[0].clientY - disY;
                if(moveY < 0) {
					moveY =  0 ;
                }
                if(moveY > document.documentElement.clientHeight - contH) {
                    moveY =document.documentElement.clientHeight - contH;
                }
				$(this).css({
					"left": moveX + sX - startX,
                    "top": moveY,
				})
			},
		})
    })
    

</script>