Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

javascript - Keeping iframe/image ratio when resizing on height

I managed to keep the iframe's ratio for when the user resizes the window on width, but I have trouble adding the logic for when the user resizes the window on height due to conflicting logic, since the resize on width already alters the height of the iframe.

This is the function that gets called when resizing:

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);
  }
}

But I believe that the problem lies in the trigger:

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';
   }
}

Got any solutions for this? (pen below)

https://codepen.io/Dragosb/pen/WNoeXRa?editors=0011

question from:https://stackoverflow.com/questions/65935212/keeping-iframe-image-ratio-when-resizing-on-height

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solved, as per the codepen (link is the same as the one in the original post):

Added a container for the iframe (if you are using a modal, that can be the container):

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);

https://codepen.io/Dragosb/pen/WNoeXRa?editors=0011


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...