仅当在div中悬停空白时显示工具提示

时间:2019-07-27 01:34:30

标签: javascript html reactjs

因此,我试图获取一个工具提示以在将div悬停时显示说明。 div内是SVG图片和一些文字。到目前为止,它仍然有效,但是仅当在div中(而不是在SVG图像的正方形中的任何地方)悬空时才显示工具提示。如果将鼠标悬停在文本或SVG图像上,它会闪烁。

我正在使用ReactJS和使用Node.js作为服务器的create-react-app。该工具提示是作为包装组件实现的,用于包装我要为其创建工具提示的卡。

代码如下:

Card.js:

import React, { Component } from 'react';
import Tooltip from './tooltip.js'

import conditionsDict from './conditions-dict.js';

class Card extends Component {

 render() {
   const id = this.props.conditionID;
   var iconURL = "";
   const description = this.props.description
   // console.log(id)
   if (conditionsDict[id] != null) {
     iconURL = conditionsDict[id].iconURL;
   } else {
     iconURL = "icons/warning.svg";
   }

   const temp = Math.round(this.props.temp);
   const pressure = (Math.round(this.props.pressure)/10); // round to integer and convert to kilopascal

   return (
     <Tooltip text={description}>
       <div className="weather-card">
         <div className="day-name">{this.props.hour}</div>
         <img className="weather-icon" alt={description} src={iconURL}></img>
         <div className="temps">
           <div className="temp">{temp}&deg;</div>
           <div className="pressure">{pressure}</div>
         </div>
       </div>
     </Tooltip>
   );
 }
}

export default Card;

tooltip.js:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import './bootstrap.css';

class Tooltip extends Component {
  constructor (props) {
    super(props)
    this.state = {opacity: false}
    this.toggle = this.toggle.bind(this)
  }

  toggle() {
    const tooltipNode = ReactDOM.findDOMNode(this)
    this.setState({
      opacity: !this.state.opacity,
      top: tooltipNode.offsetTop,
      left: tooltipNode.offsetLeft
    })
  }

  render() {
    const style = {
      zIndex: (this.state.opacity) ? 1000 : -1000,
      opacity: +this.state.opacity,
      top: (this.state.top || 0) + 20,
      left: (this.state.left || 0) - 0
    }
    return (
      <div style={{display: 'block'}}>
        <div style={{color: 'blue', display: 'inline-block'}} onMouseEnter={this.toggle} onMouseOut={this.toggle}>
          {this.props.children}
        </div>
        <div className="tooltip bottom" style={style} role="tooltip">
          <div className="tooltip-arrow"></div>
          <div className="tooltip-inner">{this.props.text}</div>
        </div>
      </div>
    )
  }
}

export default Tooltip;

除了将鼠标悬停在内容和空白区域上时工具提示闪烁外,其他所有操作均正常。

编辑:

所以我的问题是,如何获取onMouseEnter和onMouseOut处理程序以识别整个div?我尝试使用范围而不是div,并将div的display属性设置为inlineinline-block,但无济于事。

您可以在http://weather-app.timothygrindall.com/上观看该项目。如果您想查看完整的代码,可以在https://github.com/timgrindall/weather-app上看到它。

0 个答案:

没有答案