<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 100vw;
height: 100vh;
position: relative;
}
.move {
width: 100px;
height: 100px;
border-radius: 50%;
background: black;
cursor: move;
}
</style>
<body>
<div class="box">
<div class="move">
</div>
</div>
</body>
<script>
var moveBall = {
init: function () {
this.bodyWidth = document.body.clientWidth;
this.moveBox = document.getElementsByClassName('move')[0]
this.distance = this.bodyWidth / 2 - this.moveBox.clientWidth / 2
this.moveBox.style.position = 'absolute'
this.startX = 0;
this.startY = 0;
this.endX = 0;
this.endY = 0;
},
runInMobile: function () {
this.init()
this.moveBox.addEventListener('touchstart',this.ontouchstart.bind(this))
this.moveBox.addEventListener('touchmove', this.ontouchmove.bind(this))
this.moveBox.addEventListener('touchend', this.ontouchend.bind(this))
},
runInPc: function () {
this.init()
this.moveBox.addEventListener('mousedown',this.onmousedown.bind(this))
this.moveBox.addEventListener('mouseup',this.onmouseup.bind(this))
// 鼠标离开的时候也清除下
this.moveBox.addEventListener('mouseleave', ()=>{
this.moveBox.onmousemove = null
})
},
onmousedown: function (e) {//鼠标按下
this.computedStartXY(e)
this.moveBox.onmousemove =(e)=>{this.onmousemove(e)}
},
onmousemove: function (ev) {
this.computedMoveXY(ev)
},
onmouseup: function () {//鼠标抬起
this.computedEndPosition()
},
ontouchstart: function (e) { //手指按下
this.moveBox.style.transition = ''
this.computedStartXY(e.targetTouches[0])
},
ontouchmove: function (ev) {
this.computedMoveXY(ev.targetTouches[0])
},
ontouchend: function () { //手指抬起
this.computedEndPosition()
},
computedStartXY:function(root){
this.moveBox.style.transition = ''
this.startX = root.pageX - this.moveBox.offsetLeft;
this.startY = root.pageY - this.moveBox.offsetTop;
},
computedMoveXY:function(root){
this.endX = root.pageX - this.startX
this.endY = root.pageY - this.startY
this.moveBox.style.top = this.endY + 'px'
this.moveBox.style.left = this.endX + 'px'
},
computedEndPosition:function(){
let top = parseInt(this.moveBox.style.top);
let left = parseInt(this.moveBox.style.left);
this.moveBox.style.transition = 'all 0.5s linear'
if (top < 0) this.moveBox.style.top = 0 //超出屏幕让top为0
//超出屏幕更改top的值
if (this.moveBox.offsetTop + this.moveBox.clientHeight > document.documentElement.clientHeight) {
this.moveBox.style.top = (document.documentElement.clientHeight - moveBox.clientHeight) + 'px'
}
left < this.distance ? this.moveBox.style.left = 0 + 'px' : this.moveBox.style.left = (this.bodyWidth - this.moveBox.clientWidth) + 'px'
this.moveBox.onmousemove = null
},
}
moveBall.runInPc()
// moveBall.runInMobile()
PC、移动端小球拖拽吸附边界基础版
最新推荐文章于 2021-12-23 10:38:38 发布