动画效果之手机端实现垃圾桶效果

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>手机端实现垃圾桶效果</title>
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}

			#box {

				width: 300px;
				height: 500px;
				margin: 0 auto;
				border: red solid 1px;
				position: relative;
			}

			#box2 {
				margin-top: 200px;
				width: 300px;
				height: 300px;
				border: 1px solid blue;
			}

			img {

				position: absolute;
			}
		</style>
	</head>
	<body>
		<div id="box">
			<img src="img/demo.png" id='img'>
			<div id="box2"> </div>
		</div>
		<script type="text/javascript">
			var box = document.getElementById('box')
			var box2 = document.getElementById('box2')
			var img = document.getElementById('img')
			var startX, startY;
			var disX, diY;
			var x, y
			var box2Area; //box2范围

			img.addEventListener('touchstart', touchStart, false)
			img.addEventListener('touchmove', touchMove, false)
			img.addEventListener('touchend', touchEnd, false)

			//获取距离盒子的距离
			function touchStart(e) {
				startX = e.changedTouches[0].pageX - img.offsetLeft;
				startY = e.changedTouches[0].pageY - img.offsetTop;
			}

			function touchMove(e) {
				x = e.changedTouches[0].pageX - startX
				y = e.changedTouches[0].pageY - startY;
				//confined area (限制范围)
				if (x < 0) {
					x = 0;
				} else if (x > box.offsetWidth - img.offsetWidth) {
					x = box.offsetWidth - img.offsetWidth
				}
				if (y < 0) {
					y = 0;
				} else if (y > box.offsetHeight - img.offsetHeight) {
					y = box.offsetHeight - img.offsetHeight
				}
				img.style.top = y + 'px'
				img.style.left = x + 'px'
			}
			function touchEnd(e) {
				if (x > box2.offsetLeft && x < box2.offsetLeft + box2.offsetWidth &&
					y > box2.offsetTop && y < box2.offsetHeight + box2.offsetTop) {
					img.style.cssText = ""
					img.parentNode.removeChild(img)
					box2.appendChild(img)
				}else{		
					img.style.top = 0;
					img.style.left =0;
				}

			}
		</script>
	</body>
</html>

<!-- 
 手机端没有拖拽事件,因此想要实现拖拽效果的话就要借鉴原生js实现移动位置的做法
 1,触摸按下
	获取触摸位置相对于自身元素的位置 disy
	
 2,触摸移动
	获取 x,y  ,用触摸位置减去dis得到自身元素的x,y坐标
	进行限制,使其只能在页面(box)中移动
	进行移动 ele。style。top
 
 3,触目松开
	用于判断梳开后图片的为位置
	 如果不在盒子中(box2),则回到原先位置
	 如果在盒子中,则清空样式,删除原先的图片,同时将图片插入box2;
 -->



posted @ 2022-04-02 09:48  coderwcb  阅读(61)  评论(0编辑  收藏  举报