簡體   English   中英

以其他像素為單位的div高度減去div高度的百分比

[英]get div height in percent subtracted of other div height which is in pixel

我試圖獲取從高度為像素的標題中減去高度的邊欄高度的百分比。

<!--html-->
<div id="header"></div>
<div id="sidebar"></div>

<!--css-->
body{padding: 0; margin: 0;}
#header {position: fixed; width: 100%; height: 50px; background-color: yellow;}
#sidebar {position: fixed; width: 20%; background-color: blue; bottom: 0px; left: 0px; }

<!--js-->
$(document).ready(function(){   
    var bodyHeight = document.getElementByTagName("body").height();
    var headerHeight = document.getElementById("header").height();
    var sideBarHeight = (bodyHeight - headerHeight) / bodyHeight;
    $("#sidebar").css("height",sideBarHeight);
});

這是我的小提琴來檢查一下: https : //jsfiddle.net/Herza/7ks1qet1/4/

CSS應該能夠做到這一點:

 body{padding: 0; margin: 0;} #header {position: fixed; width: 100%; background-color: yellow; top:0; height: 50px; } #sidebar {position: fixed; width: 20%; background-color: blue; bottom: 0px; left: 0px; top:50px; } 
 <div id="header"></div> <div id="sidebar"></div> 

甚至與clac()

 body{padding: 0; margin: 0;} #header {position: fixed; width: 100%; background-color: yellow; top:0; height: 50px; } #sidebar {position: fixed; width: 20%; background-color: blue; bottom: 0px; left: 0px; height: calc(100% - 50px); } 
 <div id="header"></div> <div id="sidebar"></div> 

您可以在整頁模式下運行兩個代碼片段,並調整窗口大小以對其進行檢查。

除了您添加的CSS / JS麻煩之外,我不太確定這是個好主意,標題和側邊欄對於內容和固定位置而言可能太小了,無法從屏幕上溢出什么……

如果需要百分比,則應將像素轉換回百分比。

這是你的意思嗎?

https://jsfiddle.net/7fkfvwrf/

 $(document).ready(function(){ var bodyHeight = $(document).height(); var headerHeight = $("#header").height(); var sideBarHeightPercentage = 100 / bodyHeight * (bodyHeight - headerHeight); $("#sidebar").css("height",sideBarHeightPercentage + "%"); }); 
 body{padding: 0; margin: 0;} #header {position: fixed; width: 100%; height: 50px; background-color: yellow;} #sidebar {position: fixed; width: 20%; background-color: blue; bottom: 0px; left: 0px; } 
 <div id="header"></div> <div id="sidebar"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM