固定顶部后保留空间

3
我创建了一个函数,当我向下滚动时,菜单会固定在屏幕上方。但是,这样做会占用很多空间,正如你可以在我的演示fiddle中看到的那样,所有文本都被固定栏遮盖了。有没有办法在固定的.top.content之间保留更多的空间?
编辑:感谢大家的答案。我选择了Marcos的答案,因为他最先回答了,但我知道其他的方法也有效。
4个回答

2

top 固定时,你必须调整内容的 padding-top。因此,整个解决方案如下:

.top.fixed + .content {
    padding-top: 155px;
}

您编辑后的代码片段:

https://jsfiddle.net/h65x3hyb/2/


谢谢,我可以问一下你是怎么得到 padding-top: 155px; 的吗? - C.Ronaldo
1
155像素是必须显示的最小像素量。通常情况下等于页眉的高度(在这种情况下为180像素),但是使用155像素就足以显示文本了。不过,您可以通过调整该值来达到您想要的效果。祝你好运 :) - Marcos Pérez Gude
可以将标题的“top”值更改为“-105”(在这种情况下),而不是减小“height”,因为后者可能会隐藏所需的部分。 - Mark Perera
不错,最干净的解决方案 - Pete
1
是的,如果标题中没有内容,它也是有效的。 - Marcos Pérez Gude

1

你也可以给 .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>


1
请将脚本应用到其中。
$(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');
    }
  });
});

1
尝试这个,给你的

标签添加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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接