首页 > 解决方案 > 如何使用 HTML 使文本可拖动到视频上?

问题描述

我想在视频上显示文本并希望它可以在整个视频上拖动,我可以显示它但是当我拖动它然后放下时,它会出现在我的视频下方并且在它变得不可拖动之后。我正在使用 React JS。

<div className="container" > 
        <div  onDrop={this.allowDrop} onDragOver={this.dragOver}> 
        <video id="video" width="820" src="video.mp4"/>
        </div>
        <div className="overlay">
            <p draggable onDragStart={this.allowDrag} id="hey">hey there</p>
        </div>
</div>
allowDrag=(e)=>{
  e.dataTransfer.setData("text", e.target.id);
}

 allowDrop = (e)=>{
  e.preventDefault();
  var data = e.dataTransfer.getData("text");
  e.target.appendChild(document.getElementById(data));
 }

 dragOver = (e)=>{
  e.preventDefault();
 }

我的CSS看起来像这样

.container { position:relative; }
.container video {
    position:relative;
    z-index:-1;
}
.overlay {
    position:absolute;
    top:0;
    left:0;
    z-index:1;
}

有什么建议么??

标签: javascripthtmlcssreactjs

解决方案


使用鼠标指针坐标的状态

class Main extends React.Component {
  state = {
    x: 0,
    y: 0
  };
  allowDrag = e => {
    // e.preventDefault();
    e.dataTransfer.setData("text", e.target.id);
  };

  allowDrop = e => {
    e.preventDefault();
    // var data = e.dataTransfer.getData("text");
    // e.target.appendChild(document.getElementById(data));
  };

  dragOver = e => {
    e.preventDefault();
    // console.log(e.clientX, e.clientY);
    this.setState({
      x: e.clientX,
      y: e.clientY
    });
  };

  render() {
    return (
      <div className="container">
        <div onDrop={this.allowDrop} onDragOver={this.dragOver}>
          <video
            id="video"
            width="820"
            src="https://ak1.picdn.net/shutterstock/videos/1048614721/preview/stock-footage-young-student-watching-lesson-online-and-studying-from-home-young-woman-taking-notes-while-looking.mp4"
          />
        </div>
        <div
          className="overlay"
          style={{ top: this.state.y, left: this.state.x }}
        >
          <p draggable onDragStart={this.allowDrag} id="hey">
            hey there
          </p>
        </div>
      </div>
    );
  }
}

推荐阅读