<!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="./js/browser.js"></script>
<script src="./js/react.js"></script>
<script src="./js/react-dom.js"></script>
<style>
.ball{
position: relative;
top: 0;
left: 0;
width: 100px;
height: 100px;
background-color: salmon;
border-radius: 50%;
}
body{
margin: 0;
}
</style>
</head>
<body>
<div class="root"></div>
</body>
<script type="text/babel">
class Drag extends React.Component {
constructor(...args){
super(...args)
}
FnStart(ev){
this.oDiv=ev.target
this.PageX=ev.changedTouches[0].pageX-this.oDiv.offsetLeft
this.PageY=ev.changedTouches[0].pageY-this.oDiv.offsetTop
document.ontouchmove=this.FnMove.bind(this)
document.ontouchend=this.FnEnd.bind(this)
}
FnMove(ev){
this.X=ev.changedTouches[0].pageX-this.PageX
this.Y=ev.changedTouches[0].pageY-this.PageY
this.oDiv.style.left=this.X+'px'
this.oDiv.style.top=this.Y+'px'
}
FnEnd(ev){
document.ontouchmove=null
document.ontouchend=null
}
render(){
return (<div className="ball" onTouchStart={this.FnStart.bind(this)}></div>)
}
}
ReactDOM.render(<Drag/>,document.querySelector('.root'))
</script>
</html>
React实现拖拽
最新推荐文章于 2025-01-18 17:44:35 发布
这个博客展示了如何使用React创建一个触摸屏上的拖动功能。通过监听touchStart、touchMove和touchEnd事件,实现了一个圆形元素的自由拖动。代码中详细定义了组件类Drag,并在onTouchStart事件中初始化拖动状态,在onTouchMove事件中更新元素位置,最后在onTouchEnd事件中清理事件监听器。
1055

被折叠的 条评论
为什么被折叠?



