<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./browser.js"></script>
<script src="./react.js"></script>
<script src="./react-dom.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
.box {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="drag"></div>
</body>
<script type="text/babel">
window.onload = () => {
class Tz extends React.Component {
constructor(...any) {
super(...any);
this.x = 0;
this.y = 0;
}
// 点击事件
Fnstat(e) {
// 获取当前手指点击的坐标
// console.log(e.changedTouches[0].pageX,e.changedTouches[0].pageY);
// 给当前的x和y赋值
// console.log(this.x,this.y);
// 获取当前内容/标签
// console.log(e.target,7777);
// 获取当前元素距离视口的位置
// console.log(e.target.offsetLeft);
// console.log(e.changedTouches[0].pageX-e.target.offsetLeft);
// console.log(e.changedTouches[0].pageX);
this.x = e.changedTouches[0].pageX - e.target.offsetLeft;
this.y = e.changedTouches[0].pageY - e.target.offsetTop;
document.ontouchmove = this.FnMove.bind(this); // 指向的是当前元素
// document.ontouchmove=this.FnMove // 指向的是doment
document.ontouchend = this.FnEnd.bind(this);
}
// 触摸/移动事件
FnMove(e) {
this.disX = e.changedTouches[0].pageX - this.x;
this.disY = e.changedTouches[0].pageY - this.y;
// 获取当前移动到的值
// console.log(this.disX,this.disY);
// 移动当前的位置
e.target.style.left = this.disX + "px";
e.target.style.top = this.disY + "px";
}
// 失去焦点/消除默认操作
FnEnd() {
document.ontouchmove = null;
document.ontouchend = null;
}
render() {
return (
<div onTouchStart={this.Fnstat.bind(this)} className="box"></div>
);
}
}
ReactDOM.render(<Tz />, document.querySelector(".drag"));
};
</script>
</html>
上图引入的react依赖包
链接: https://pan.baidu.com/s/14Ju9KMT9ORjiYPLqHSMOAQ
提取码: cihi