我创建了一个函数,当我向下滚动时,菜单会固定在屏幕上方。但是,这样做会占用很多空间,正如你可以在我的演示fiddle中看到的那样,所有文本都被固定栏遮盖了。有没有办法在固定的
编辑:感谢大家的答案。我选择了Marcos的答案,因为他最先回答了,但我知道其他的方法也有效。
.top
和.content
之间保留更多的空间?编辑:感谢大家的答案。我选择了Marcos的答案,因为他最先回答了,但我知道其他的方法也有效。
.top
和.content
之间保留更多的空间?当 top
固定时,你必须调整内容的 padding-top
。因此,整个解决方案如下:
.top.fixed + .content {
padding-top: 155px;
}
您编辑后的代码片段:
你也可以给 .content
添加一个类:
$(function() {
var $top = $('.top'),
$content = $('.content');
$(window).on('scroll', function() {
if ($(window).scrollTop() > 75) {
$top.addClass('fixed');
$content.addClass('margin');
} else {
$top.removeClass('fixed');
$content.removeClass('margin');
}
});
});
.top {
top: 0;
height: 180px;
width: 100%;
background-color: red;
box-sizing: border-box;
}
.top.fixed {
height: 75px;
position: fixed;
-webkit-transition: height 0.5s;
transition: height 0.5s;
}
.content {
height: 900px;
background-color: green;
}
.content.margin {
margin-top: 180px;
/*height of top*/
}
p {
margin-top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top">
</div>
<div class="content">
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum
</p>
</div>
$(function()
{
$top = $('.top');
$(window).on('scroll', function()
{
if ($(window).scrollTop() > 75)
{
$top.addClass('fixed');
$('.content').css('padding-top:','196px');
}
else
{
$top.removeClass('fixed');
$('.content').css('padding-top:','0');
}
});
});
标签添加padding,使用jquery为内容添加margin。
$(function()
{
$top = $('.top');
$(window).on('scroll', function()
{
if ($(window).scrollTop() > 75)
{
$top.addClass('fixed');
$(".content").css("marginTop","152px");
}
else
{
$top.removeClass('fixed');
$(".content").css("marginTop","0px");
}
});
});
p
{
margin: 0;
padding-top:20px;
}