繁体   English   中英

javascript偏移宽度和高度(百分比)

[英]javascript offset width and height in percentage

我试图获取图像的宽度和高度相对于“旧的” 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) + '%';

在window.resize上使用此脚本,但它始终提供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}%`; }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM