首页 > 解决方案 > 在 React/TS 上调整窗口大小、居中并保持纵横比时调整图像大小

问题描述

我想在调整窗口大小时调整图像大小。我想将此图像居中到容器 div 元素。我还想在 4 面有填充。(上/左/下/右:例如 15%)

现场演示https ://react-ts-f4jemk.stackblitz.io

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

它应该是这样的:

样本

调整窗口大小时,图像应根据窗口大小变大或变小。在这种情况下,我想在顶部、左侧、底部和右侧保持纵横比和空白,以便图像可见并以 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()作品,我的计算是错误的。我该如何正确处理这种情况?我怎样才能正确计算?

标签: javascriptcssreactjs

解决方案


我更新了您的函数以根据图像的纵横比调整图像大小

  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


推荐阅读