问题描述
当用户调整窗口宽度时,我设法保持 iframe 的比例,但是由于逻辑冲突,我无法添加用户调整高度窗口大小的逻辑,因为调整宽度大小已经改变了高度的 iframe。
function calculateAspectRatioFit(width,height,ratio) {
if(height) {
let width = ((length)/(Math.sqrt((1)/(Math.pow(ratio,2)+1))));
return Math.round(width);
} else if(width) {
let height = ((width)/(Math.sqrt((Math.pow(ratio,2)+1))));
return Math.round(height);
}
}
但我认为问题出在触发器上:
const resizeHandler = (e) => {
console.log("inside ",parseInt(iframeHeight),iframeElement.offsetHeight);
if(parseInt(iframeWidth) > iframeElement.offsetWidth) {
// overwrite inline styling
iframeElement.style.csstext = 'height: ' + calculateAspectRatioFit(iframeElement.offsetWidth,null,iframeRatio) + 'px!important';
} else if (parseInt(iframeHeight) > window.innerHeight) {
iframeElement.style.csstext = 'width: ' + calculateAspectRatioFit(null,iframeElement.offsetHeight,iframeRatio) + 'px!important';
}
}
对此有任何解决方案吗? (下面的钢笔)
https://codepen.io/Dragosb/pen/WNoeXRa?editors=0011
解决方法
已解决,根据codepen(链接与原帖中的链接相同):
为 iframe 添加了一个容器(如果您使用的是 modal,那可以是容器):
const resizeHandler = (e) => {
// get container measures
let computedContainerStyling = getComputedStyle(iframeContainer);
let containerWidth = parseInt(computedContainerStyling.width);
let containerHeight = parseInt(computedContainerStyling.height);
if ( (containerWidth / iframeRatio) > containerHeight){
iframeHeight = containerHeight;
iframeWidth = containerHeight * iframeRatio;
} else {
iframeWidth = containerWidth;
iframeHeight = containerWidth / iframeRatio;
}
iframeElement.style.width = Math.floor(iframeWidth) + 'px';
iframeElement.style.height = Math.floor(iframeHeight) + 'px';
}
window.addEventListener('resize',resizeHandler,false);