需要实现的需求如下
直接上代码
HTML:
<div class="container" id="container">
<div class="controlDiv" id="controlDiv">
<div
class="centerCircle"
id="centerCircle"
@touchstart="start"
@touchmove="move"
@touchend="end">
</div>
</div>
</div>
javascript:
import {defineComponent, onMounted} from "vue";
export default defineComponent({
setup(prop,content) {
let controlDiv =''
let circleDiv = ''
let maxW = 0
let maxH = 0
let oL = 0
let oT = 0
let touchClientX = 0
let touchClientY = 0
onMounted(() => {
controlDiv = document.querySelector('#controlDiv')
circleDiv = document.querySelector('#centerCircle')
console.log(circleDiv.offsetWidth, circleDiv.offsetHeight)
maxW = controlDiv.offsetWidth
maxH = controlDiv.offsetHeight
})
const start = (e) => {
var ev = e || window.event;
var touch = ev.targetTouches[0];
oL = touch.clientX - circleDiv.offsetLeft
oT = touch.clientY - circleDiv.offsetTop
touchClientX = touch.clientX
touchClientY = touch.clientY
console.log(oL, oT)
document.addEventListener('touchmove', defaultEvent, { passive: false })
}
const move = (e) => {
var ev = e || window.event
var touch = ev.targetTouches[0]
var oLeft = touch.clientX - oL
var oTop = touch.clientY - oT
if(oLeft - 30 < 0) {
oLeft = 30
} else if(oLeft + 30 >= maxW) {
oLeft = maxW-30
}
if(oTop - 30 < 0) {
oTop = 30
} else if(oTop + 30 >= maxH) {
oTop = maxH-30
}
let tan = (150 - oTop)/(oLeft - 150)
if(Math.abs(oLeft - 150) >= 20 || Math.abs(150 - oTop)>= 20){
if((tan <= -1) || (tan >= 1)){
circleDiv.style.top = oTop + 'px'
circleDiv.style.left = 150 + 'px'
}else if((tan > -1) || (tan < 1)){
circleDiv.style.top = 150 + 'px'
circleDiv.style.left = oLeft + 'px'
}
}else{
circleDiv.style.top = oTop + 'px'
circleDiv.style.left = oLeft + 'px'
}
}
const end = (e) => {
circleDiv.style.left = (touchClientX - oL) + 'px'
circleDiv.style.top = (touchClientY - oT) + 'px'
document.removeEventListener("touchmove", defaultEvent, { passive: true })
}
function defaultEvent(e) {
e.preventDefault();
}
return { start, move, end }
}
});
CSS:
.controlDiv{
position: relative;
width: 300px;
height: 300px;
background: #ebebeb;
margin: 200px auto;
border-radius: 50%;
}
.centerCircle{
width: 65px;
height: 65px;
background: #fff;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border-radius: 50%;
box-shadow:0px 0px 30px #a7a7a7;
}