将div高度减去百分比减去以像素为单位的其他div高度

时间:2015-03-19 14:52:34

标签: javascript html css

我试图获得一个侧边栏高度的百分比,从高度以像素为单位的标题中减去高度。

<!--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/

2 个答案:

答案 0 :(得分:0)

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问题之外,我不太确定这是一个好主意,标题和侧边栏可能对于内容和固定位置而言太小,屏幕溢出的内容无法访问......

答案 1 :(得分:0)

如果您想要百分比,则应将像素转换回百分比。

这是你的意思吗?

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>