调整窗口大小,居中并在React / TS上保持宽高比时调整图像大小

时间:2019-05-18 18:23:03

标签: javascript css reactjs

我想在调整窗口大小时调整图像大小。我想将此图像居中放置到容器div元素上。我也想在4边上都有填充物。 (顶部/左侧/底部/右侧:例如15%)

实时演示https://react-ts-f4jemk.stackblitz.io

实时编辑器https://stackblitz.com/edit/react-ts-f4jemk

它应该是这样的:

sample

调整窗口大小时,图像应根据窗口大小变大或变小。在这种情况下,我要保持宽高比,并在顶部,左侧,底部和右侧保留空白,以便图像可见并位于div的中心。

到目前为止我尝试过的事情

 updateDimensions() {

    let imgHeight = this.state.imgHeight
    let imgWidth = this.state.imgWidthMax

    let w = window,
      d = document,
      documentElement = d.documentElement,
      body = d.getElementsByTagName('body')[0],
      width = w.innerWidth || documentElement.clientWidth || body.clientWidth,
      height = w.innerHeight || documentElement.clientHeight || body.clientHeight

    if (imgWidth && imgWidth > 0) {
      imgWidth = imgWidth + width - this.state.width
      imgHeight = imgHeight + height - this.state.height
      const ratioW = width / imgWidth
      const ratioH = height / imgHeight
      this.setState({ width: width, height: height, imgHeight, imgWidth })
      return
    }

    this.setState({ width: width, height: height, imgHeight, imgWidth })

  }
  componentWillMount() {
    this.updateDimensions()
  }
  componentDidMount() {
    window.addEventListener("resize", this.updateDimensions)
    setTimeout(() => {
      const imgHeight: number = this.imgEl.clientHeight
      const imgWidth: number = this.imgEl.clientWidth
      this.setState({ imgHeight, imgWidth, imgHeightMax: imgHeight, imgWidthMax: imgWidth })

    }, 1000)
  }
  componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions)
  }

我也尝试通过纯CSS做到这一点。但是,宽度或高度会变大,然后浏览器的高度/宽度会变大。

.img {
   width: auto; // or 100%
   height: 100%; // or auto
}

我的updateDimensions()工作正常,但是我的计算是错误的。我该如何正确处理这种情况?我该如何正确计算?

1 个答案:

答案 0 :(得分:1)

我更新了您的功能,以根据图像的宽高比调整图像的大小

  updateDimensions() {
    let w = window,
      d = document,
      documentElement = d.documentElement,
      body = d.getElementsByTagName("body")[0],
      inner = d.querySelector(".inner");

    //this calculates the padding %
    const height = inner.clientHeight - inner.clientHeight * 0.15;
    const width = inner.clientWidth - inner.clientWidth * 0.15;

    let imgWidth = width;
    //calculates hight base os aspect ratio
    let imgHeight = (imgWidth * height) / width;

    //if height is greater than the inner container, set the maximun size and recalculate width base on max-height
    if (imgHeight > height) {
      imgHeight = height;
      imgWidth = (imgHeight * width) / height;
    }

    this.setState({ width, height, imgWidth, imgHeight });
  }

这是在线编辑器上的更新代码:https://stackblitz.com/edit/react-ts-jbzynn?file=index.tsx