鼠标

时间:2017-06-18 05:36:21

标签: javascript css css3 reactjs

我正在尝试创建一个React Component来缩放图像,缩放的图像跟随鼠标。

我已经创建了一支笔来展示我到目前为止所做的工作:React Zoom

以下是代码:

class ProductGallery extends React.Component {
  constructor (props) {
    super(props)

    this.state = {
      imgZoomed: false,
      mouseX: undefined,
      mouseY: undefined
    }

    this.zoomImage = this.zoomImage.bind(this)
    this.unZoomImage = this.unZoomImage.bind(this)
    this.moveMouseImg = this.moveMouseImg.bind(this)
  }

  zoomImage () {
    this.setState({
      imgZoomed: true
    })
  }

  unZoomImage () {
    this.setState({
      imgZoomed: false
    })
  }

  moveMouseImg (e) {
    const {
      top: offsetTop,
      left: offsetLeft
    } = e.target.getBoundingClientRect()

    const x = ((e.pageX - offsetLeft) / e.target.width) * 100
    const y = ((e.pageY - offsetTop) / e.target.height) * 100

    this.setState({
      mouseX: x,
      mouseY: y
    })
  }

  render () {
    const transform = {
      transformOrigin: `${this.state.mouseX}% ${this.state.mouseY}%`
    }

    const classes = Object.assign({}, transform, {
      transform: this.state.imgZoomed ? 'scale(2.0)' : 'scale(1.0)',
      maxHeight: '615px',
      maxWidth:  '100%',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      backgroundSize: 'cover',
      transition: 'transform .1s ease-out'
    })

    const divStyles = {
      height: '615px',
      width:  '615px',
      float: 'left',
      marginLeft: '10px',
      overflow: 'hidden',
      borderStyle: 'solid'
    }

    return (
      <div style={divStyles}>
        <img
     src="http://www.planwallpaper.com/static/images/maxresdefault_8yZPhSS.jpg"
          style={classes}
          alt="dmsak"
          onMouseOver={this.zoomImage}
          onMouseOut={this.unZoomImage}
          onMouseMove={this.moveMouseImg}
          />
      </div>
    )
  }
}

React.render(<ProductGallery />, document.getElementById('app'));

问题是当我移动鼠标时,组件才开始“摇动”!我使用的是2.0,但如果我将其更改为1.5(transform: scale(1.5)),则问题只发生在图像的边缘。

我该如何解决?

0 个答案:

没有答案