javascript - 在 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()
作品,我的计算是错误的。我该如何正确处理这种情况?我怎样才能正确计算?
解决方案
我更新了您的函数以根据图像的纵横比调整图像大小
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
推荐阅读
- python - 如何在 JSON 数组 python 中访问 JSON 对象?
- vba - 无法在 VBA 中使用 Lapack DGETRF/DGETRI 反转矩阵
- swiftui - 如何预览依赖于 PresentationMode 的 SwiftUI 按钮?
- python - 如何使用 tkinter 事件“继续”或暂停不同的 while 循环?
- node.js - 即使在 knex.destroy() 之后,承诺仍然悬而未决
- javascript - 其他组件中的道具未定义 React
- unity3d - 当不再与玩家发生碰撞时,无法弄清楚如何阻止僵尸造成伤害
- python - BeautifulSoup 找不到标签
- python - 在参数描述之后有等号有什么意义
- bash - 如何在不使用 bash -x 的情况下将命令保存在变量中并在执行前打印翻译后的命令