Javascript偏移宽度和高度的百分比

javascript offset width and height in percentage

本文关键字:高度 百分比 Javascript      更新时间:2023-09-26

我正试图获得一个图像的宽度和高度相对于'旧' 100%的宽度和高度的身体(全屏打开)。

找到一个脚本巫婆给出的宽度和高度百分比:

thisWidth = Math.round(((content.offsetWidth/
               document.getElementsByTagName('BODY')[0].clientWidth)-0)*100) + '%';
thisHeight = Math.round(((content.offsetHeight/
                document.getElementsByTagName('BODY')[0].clientHeight)-0)*100) + '%';

在窗口上使用这个脚本。调整大小,但它总是给出100%(这是合乎逻辑的,因为它会重新计算新的大小,因此它总是100%)。

但是我需要的是与打开窗口大小相关的百分比,这样我就可以按新的宽度和高度百分比调整图像的大小。

希望足够清楚,如果没有,我想再试一次!由于

还没有经过测试,但这可能会对您有所帮助。代码注释应该让你知道发生了什么:

// Something to compare to.
const initialWidth = document.body.clientWidth;
const initialHeight = document.body.clientHeight;
window.addEventListener('resize', () => {
  // Get the width of something else, in this case, the body.  
  const width = document.body.clientWidth;
  const height = document.body.clientHeight;
  
  // Convert to percentages.
  const widthInPercent = Math.round((initialWidth / width) * 100);
  const heightInPercent = Math.round((initialHeight / height) * 100);
  
  // Do something with the results.
  document.body.innerHTML = `Width: ${widthInPercent}% Height: ${heightInPercent}%`;
});