问题: http://jsfiddle.net/um2b98we/5/
我有一个小问题。我尝试创建一个导航,其中子(蓝色框)div 的屏幕高度为 75%。我完全没有问题,只要父项(绿色框)处于相对位置即可。
但是,当我向下滚动时,我希望父级固定在屏幕顶部。然而, child 将高度更改为父级的 75%,但我需要它保持屏幕的 75% 高度
示例代码,请转到上面的链接:
#scroll, #header, #one, #two {width: 100%}
#scroll {height: 2000px;}
#one {
background: red;
height:50px;
}
#two {
background: green;
height:50px;
}
#two.fixed{
position:fixed;
top:0;
}
#sub {
position: absolute;
height: 75%;
width: 80%;
background: blue;
margin-top:50px;
}
<div id="scroll">
<div id="header">
<div id="one"></div>
<div id="two">
<div id="sub"></div>
</div>
</div>
</div>
我已经尝试修复它很长时间了,但没有成功。我将不胜感激。
最佳答案
你可以用 javascript 给 div 高度:
$(window).bind('scroll', function(){
var windowHeight = $(window).height();
$('#two').toggleClass('fixed',$(window).scrollTop() > 50);
$('#sub').css('height',windowHeight *.75);
});
或在应用固定类后添加它:
$(window).scroll(function() {
var scroll = $(window).scrollTop(),
windowHeight = $(window).height();
if (scroll >= 50) {
$("#two").addClass("fixed");
$('#sub').css('height', windowHeight *.75);
} else {
$("#two").removeClass("fixed");
}
});
关于javascript - div 百分比高度不按预期工作 - 在固定 div 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30678717/