的JavaScript。使用React可拖动div

问题描述 投票:0回答:1

我正试图制作一个可拖动的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"
    })
javascript html css reactjs
1个回答
0
投票

问题出在“tech”div的“row”类中。删除它,一切都开始按预期工作。哈哈。

<div className="tech border rounded"
© www.soinside.com 2019 - 2024. All rights reserved.