需求:滑动手势最大不能超过一个半径为50的圆形,超出围绕圆形边线滑动
这里只提供一个思路,下面代码可以运行,但是要使用需要改成自己的参数
<div style="width: 100%;height: 100vh;display: flex;justify-content: center;align-items: center;"><div style="width: 100px;height: 100px;background: #888;border-radius: 50%;"><div id="myElement" style="width: 20px;height: 20px;border-radius: 50%;background: red;position: absolute;"></div></div>
</div>
<script>var circleRadius = 50; // 圆形半径// 获取圆心坐标var circleCenterX = window.innerWidth / 2;var circleCenterY = window.innerHeight / 2;// 添加滑动事件监听器document.addEventListener('mousemove', handleMouseMove);// 处理滑动事件function handleMouseMove(event) {// 获取鼠标相对于窗口的坐标var mouseX = event.clientX;var mouseY = event.clientY;// 计算鼠标位置相对于圆心的偏移量var offsetX = mouseX - circleCenterX;var offsetY = mouseY - circleCenterY;// 计算鼠标位置相对于圆心的距离var distance = Math.sqrt(offsetX * offsetX + offsetY * offsetY);// 如果距离大于半径,则将偏移量按比例缩小到半径范围内if (distance > circleRadius) {var ratio = circleRadius / distance;offsetX *= ratio;offsetY *= ratio;}// 计算围绕圆心的新坐标var newX = circleCenterX + offsetX;var newY = circleCenterY + offsetY;// 更新元素位置(这里假设要更新一个元素的位置)var element = document.getElementById('myElement');element.style.left = newX + 'px';element.style.top = newY + 'px';}
</script>
示例
此示例是一个鼠标按下放开的示例,手机端可以替换为手机的事件
<div style="width: 100%;height: 100vh;display: flex;justify-content: center;align-items: center;"><div style="width: 100px;height: 100px;background: #888;border-radius: 50%;position: relative;display: flex;justify-content: center;align-items: center;"><div onmousedown="mousedown(event)" onmouseup="mouseup(event)" id="myElement" style="width: 20px;height: 20px;border-radius: 50%;background: red;position: relative;"></div></div>
</div>
<script>var circleRadius = 50; // 圆形半径// 获取圆心坐标var circleCenterX = 0var circleCenterY = 0// 添加滑动事件监听器document.addEventListener('mousemove', handleMouseMove);function mousedown(event) {circleCenterX = event.clientX;circleCenterY = event.clientY;}function mouseup() {circleCenterX = 0circleCenterY = 0var element = document.getElementById('myElement');element.style.left = '0px';element.style.top = '0px';}// 处理滑动事件function handleMouseMove(event) {// 获取鼠标相对于窗口的坐标var mouseX = event.clientX;var mouseY = event.clientY;// 计算鼠标位置相对于圆心的偏移量var offsetX = mouseX - circleCenterX;var offsetY = mouseY - circleCenterY;// 计算鼠标位置相对于圆心的距离var distance = Math.sqrt(offsetX * offsetX + offsetY * offsetY);// 如果距离大于半径,则将偏移量按比例缩小到半径范围内if (distance > circleRadius) {var ratio = circleRadius / distance;offsetX *= ratio;offsetY *= ratio;}// 计算围绕圆心的新坐标var newX = offsetX;var newY = offsetY;if(circleCenterX >0) {// 更新元素位置(这里假设要更新一个元素的位置)var element = document.getElementById('myElement');element.style.left = newX + 'px';element.style.top = newY + 'px';}}
</script>