我使用的是Reactjs,我想要得到一个img元素的高度,我想保持img的比例,所以我在css中像这样设置图像。
.img {
position: fixed;
z-index: 999;
width: 30%;
height: auto;
left: 5%;
object-fit: fill;
}
请注意,这里的高度是"auto“。
现在,我只是尝试在componentDidMount()中获得它的呈现高度,如下所示:
componentDidMount() {
const height = document.getElementById('ImgID').clientHeight;
const width = document.getElementById('ImgID').clientWidth;
console.log(height, width)
}
I检查只是在控制台中打印结果,但是日志显示高度为0,宽度为252 (显式宽度)。
事实是,图像出现在屏幕上,它的高度在视觉上不是0。然后,我尝试通过打印来手动检查属性'clientHeight‘:
console.log(document.getElementById('ImgID').attributes)
通过展开'style > ownerElement > clientHeight‘,我看到客户端高度是49,它不是零,但我就是得不到正确的值:/。
我正在寻找在这种情况下获得高度的解决方案,它可以是Javascript/css,或者两者兼而有之。我尽量避免使用JQuery,因为React使用的是虚拟DOM,而不是浏览器DOM。
下面是我从@ııı得到的答案所建议的getBoundingClientRect()
发布于 2019-02-19 01:05:29
这实际上是因为当componentDidMount()
执行时图像还没有加载。<img>
在DOM中,但height
在图像加载之前是未知的(除非从CSS显式设置)。解决方案是在onLoad
中查询高度。请参阅下面的测试:
class Test extends React.Component {
componentDidMount() {
//console.log(this.refs.img.getBoundingClientRect().height);
console.log('componentDidMount', this.refs.img.clientHeight);
}
imageLoaded = () => {
console.log('imageLoaded', this.refs.img.clientHeight);
}
render() {
return <img src="http://placekitten.com/200/200"
ref="img"
onLoad={this.imageLoaded}
/>;
}
}
ReactDOM.render(<Test />, document.getElementById('app'));
<script src="http://unpkg.com/react/umd/react.production.min.js"></script>
<script src="http://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<div id="app"></div>
https://stackoverflow.com/questions/54752137
复制相似问题