我正在尝试制作一个可拖动的 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"
})
最佳答案
问题出在“tech”div 的“row”类中。删除它,一切都开始正常工作。哈哈。
<div className="tech border rounded"
关于Javascript。带有 React 的可拖动 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53553517/