簡體   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