javascript - Javascript。使用 React 的可拖动 div
问题描述
我正在尝试制作一个可拖动的 div,但我遇到了令人困惑的行为。该解决方案是从 w3schools 复制的,它适用于他们,但不适用于我。随着鼠标的轻微移动,div 总是向左移动,即使鼠标上下移动,只有向右大幅度移动,div 才会跟随光标。
div.js
constructor(props){
super(props)
this.state = {
x: this.props.x,
y: this.props.y,
}
this.dragMouseDown = this.dragMouseDown.bind(this)
this.elementDrag = this.elementDrag.bind(this)
this.closeDragElement = this.closeDragElement.bind(this)
this.reff = React.createRef()
}
componentDidMount(){
this.pos1 = 0
this.pos2 = 0
this.pos3 = 0
this.pos4 = 0
}
dragMouseDown(e) {
e.preventDefault()
this.pos3 = e.clientX
this.pos4 = e.clientY
document.onmouseup = this.closeDragElement
document.onmousemove = this.elementDrag
}
elementDrag(e) {
e.preventDefault()
this.pos1 = this.pos3 - e.clientX
this.pos2 = this.pos4 - e.clientY
this.pos3 = e.clientX
this.pos4 = e.clientY
this.setState({
y:(this.reff.current.offsetTop - this.pos2) + "px",
x:(this.reff.current.offsetLeft - this.pos1) + "px",
})
}
closeDragElement() {
document.onmouseup = null
document.onmousemove = null
}
render(){
return (
<div className="tech row align-items-center justify-content-center border rounded"
style={{left: this.state.x, top: this.state.y}}
onMouseDown={this.dragMouseDown}
ref={this.reff}
>
<img className="technology-icon" src={image} alt="technology_logo"></img>
<span className="ml-1">{this.props.name}</span>
</div>
)
}
带有这个 div 和容器的 CSS
.t_d{
position: relative;
width: 80%;
height: 100%;
overflow: hidden;
overflow-x: auto;
overflow-y: auto;
border: 1px solid black;
}
.tech{
width: 150px;
height: 50px;
border-radius: 6px;
position: absolute;
}
和 html (行 - 一个 div 组件数组)
<div id="app" style="height: 100%">
<div className="fluid-container" style={{height: "100%"}}>
<nav className="navbar navbar-dark bg-dark" id="nav">
<a className="navbar-brand" href="#">Navbar</a>
</nav>
<div className="t_d">
{rows}
</div>
</div>
</div>
另外,我尝试执行以下代码之类的操作,并且可以正常工作,但是我不喜欢 div 移动到光标的事实
this.setState({
y: e.clientY - this.height + this.td.scrollTop + "px",
x: e.clientX + this.td.scrollLeft + "px"
})
解决方案
问题出在“技术” div 中的“行”类中。删除它,一切都开始正常工作。哈哈。
<div className="tech border rounded"
推荐阅读
- angular - 在 webrtc 中没有触发 icecandidate 事件
- mysql - MYSQL 状态最大值
- powershell - 在 PowerShell 中,将复杂对象 (SmoServer) 传递给 ArgumentList 中的后台作业 - 卡在“未启动”中
- python-3.x - GridSizer 没有正确放置我的元素
- css - 在引导程序 4 中轻松更改水平表单列对齐
- perl - 输出被截断的字符串的行号时,Perl 截断为 Off-by-2
- google-sheets - 谷歌表格 - 按日期分组按项目的行排名
- css - 如何将css文本动画扩展到多行?
- x86 - 英特尔 PIN 工具:获取 EFLAGS 值的踪迹
- sql - 基于另一行的唯一列数