【问题标题】:How do I link to top of a section on the page minus the height of a fixed nav-bar?如何链接到页面上某个部分的顶部减去固定导航栏的高度?
【发布时间】:2014-10-14 23:30:33
【问题描述】:

当我单击固定导航栏上的链接时,它会跳转到页面上的特定部分,但固定导航栏的高度会溢出。我怎样才能减去那个高度?这需要 javascript/jquery 吗?

<div id="fixedNavWrapper">
    <div id="navLinks">
        <ul>
            <li><a href="#about">ABOUT ME</a></li>
            <li><a href="#portfolio">PORTFOLIO</a></li>
        </ul>
    </div>
</div>

<section id="about" class="section">
    <h2>ABOUT ME</h2>
</section>

.CSS:

#fixedNavWrapper {
  position: fixed;
  z-index: 1;
  width: 100%;
  top: 0;
  left: 0;
}

#navLinks {
  text-align: center;
  width: 100%;
  height: 57px;
  background: #000000;
}

#navLinks ul {
  list-style: none;
  margin: 0;
  padding: 5px;
  display: inline-block;
} 

#navLinks ul li {
  margin: 0;
  padding: 0;
  display: inline;
}

#navLinks ul li a {
  text-decoration: none;
  display: block;
  float: left;
  padding: 0 65px;
  height: 45px;
  line-height: 45px;
}

【问题讨论】:

标签: html css hyperlink navbar fixed


【解决方案1】:

我认为你不能用 css 做到这一点。但是,您可以使用 jQuery 来执行此操作。很简单:

HTML(向 li 元素添加类以在 jQuery 代码中识别它们):

<div id="fixedNavWrapper">
    <div id="navLinks">
        <ul>
            <li class="about"><a href="#about">ABOUT ME</a></li>
            <li class="portfolio"><a href="#portfolio">PORTFOLIO</a></li>
        </ul>
    </div>
</div>

<section id="about" class="section">
    <h2>ABOUT ME</h2>
</section>

JS(使用事件 .click 将你的“身体”移动到正确的位置)

$('li.about').click(function(){
 positionabout = $('#about').offset().top - $('#fixedNavWrapper').height(); // Position of #about - nav height = correct position
 $("html, body").animate({scrollTop:positionabout}, '500', 'swing');
})
$('li.portfolio').click(function(){
 positionport = $('#portfolio').offset().top - $('#fixedNavWrapper').height();
 $("html, body").animate({scrollTop:positionport}, '500', 'swing');
})

【讨论】:

    【解决方案2】:

    有点笼统:

    $('.navbar li a').click(function () {
    
        var speed = 500;
        var easing = 'swing';
        var topMargin = 10;
    
        var href = $(this).attr("href");
        var name = href.substr(href.indexOf("#") + 1);
        var $link = $("a[name='" + name + "']");
    
        positionabout = $link.offset().top - $('.navbar').height() - topMargin;
        $("html, body").animate({scrollTop: positionabout}, speed, easing);
    
        return false;
    });
    

    【讨论】:

      猜你喜欢
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多