当我使用 ReactJS 编写 Web 应用程序时,我想在目标 div 容器中创建视频播放器。
因此,我在“componentDidMount”函数中进行了编码,如下所示:
componentDidMount(){
const box = document.getElementById('video-box');
//use the ThirdPartyObject player API to create the player
player = ThirdPartyObject('#video-box').videoPlayer({
'width':box.clientWidth,
'height':box.clientWidth * 9 / 16,
'vid' : vid,
'df': '1'
});
}
但是,实际上,我让播放器比实际框更宽。如下:
所以,我在页面刷新时在chrome的控制台中测试了代码“document.body.clientWidth”。一开始结果是1440,最后变成了1423。
那么,这是为什么呢?我怎样才能做正确的事?
最佳答案
当我做一些实验时,如下:
componentDidMount(){
const box = document.getElementById('video-box');
//use the ThirdPartyObject player API to create the player
console.log('before player init: ' + box.clientWidth)
player = ThirdPartyObject('#video-box').videoPlayer({
'width':box.clientWidth,
'height':box.clientWidth * 9 / 16,
'vid' : vid,
'df': '1'
});
console.log('after player init: ' + box.clientWidth)
}
我喜欢在玩家初始化之后,输出宽度是正确的。 我改变了播放器的风格以使其正常工作。虽然我知道这不是完美的方式。
componentDidMount(){
const box = document.getElementById('video-box');
//use the ThirdPartyObject player API to create the player
console.log('before player init: ' + box.clientWidth)
player = ThirdPartyObject('#video-box').videoPlayer({
'width':box.clientWidth,
'height':box.clientWidth * 9 / 16,
'vid' : vid,
'df': '1'
});
player.style.width = box.clientWidth
player.style.height = box.clientWidth *9 /16
}
关于javascript - 在reactjs应用程序中,如何获得dom元素的正确宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42505056/