【问题标题】:Is it possible to position a text depending on the position of the mouse with React JS?是否可以使用 React JS 根据鼠标的位置定位文本?
【发布时间】:2018-11-29 19:10:49
【问题描述】:

我有一个简单的div,有一个函数可以获取鼠标在这个div里面的坐标。

<div onMouseMove={this._onMouseMove}></div>

这个函数保存状态,div的坐标

constructor() {
    super();
    this.state = {
      selectedVariables: [],
      mouseCordinates: {x: 0, y: 0}
    };
  }

  _onMouseMove = e => {
    this.setState({x: e.screenX, y: e.screenY});
    console.log(`x: ${e.screenX}, y: ${e.screenY}`);
  }

现在我想在这些具体坐标中在这个 div 中绘制变量 helloWorld

helloWorld = 'Hello World';

<div onMouseMove={this._onMouseMove}>
  // Into this div it must paint the variable according to the coordinates
</div>

这可能吗?有什么想法吗?

感谢您的帮助。

【问题讨论】:

  • 我的问题很简单:它的 javascript。为什么不呢?您是否尝试过您的代码?
  • 感谢您的回复,但我认为您不理解我的问题。我的代码运行良好,但不符合我的要求。
  • 看起来你只是想当鼠标移动时,让 div 跟随。最重要的是,您想在其中显示一些文本吗?好吧,onMouseMove 仅从它分配的 div 进行监视,因此您希望您的画布或工作区能够移动鼠标。然后你只需要定义一个 div 并引用其中的属性。然后在您的 mousemove 中,将使用适当的 ID 移动 div。

标签: javascript reactjs onmousemove


【解决方案1】:

您可以使用以下答案作为起点:

helloWorld = 'Hello World';

<div onMouseMove={this._onMouseMove}>
  // Into this div it must paint the variable according to the coordinates
<div style=`position:relative;left:${this.state.mouseCoordinates.x},
 top:${this.state.mouseCoordinates.y}`>{helloWorld}</div>
</div>

我知道我的样式会出错,因为我使用 x 和 y 坐标在 position:relative 中指定 lefttop,但我希望您可以围绕该部分进行调整以达到预期的结果.

【讨论】:

  • 感谢您的回复,这样做会很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
  • 2011-08-12
  • 2017-09-03
  • 2013-04-21
  • 2012-12-25
相关资源
最近更新 更多