我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。


当前回答

用可链接id来提供导航栏高度的隐藏span标签怎么样?

#head1 {
  padding-top: 60px;
  height: 0px;
  visibility: hidden;
}


<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>

这里是小提琴:http://jsfiddle.net/N6f2f/7

其他回答

你可以只使用CSS而不需要任何javascript。

给你的锚一个类:

<a class="anchor" id="top"></a>

然后,通过将锚定位为块元素并相对定位,您可以将锚定位在比它在页面上实际出现的位置更高或更低的偏移量。-250px将锚点向上定位250px

a.anchor {
    display: block;
    position: relative;
    top: -250px;
    visibility: hidden;
}

我找到了这个解决方案:

<a name="myanchor">
    <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</a>

这不会在内容和锚链接中产生任何差距,效果非常好。

我也曾面临过类似的问题,不幸的是,在实施了上述所有解决方案后,我得出了以下结论。

我的内部元素有一个脆弱的CSS结构和实现位置相对/绝对发挥,完全打破了页面设计。 CSS不是我的强项。

我写了这个简单的滚动js,它解释了由于标题引起的偏移,并将div重新定位到下面大约125像素。请用你认为合适的。

HTML

<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->

JavaScript

 $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
&& location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offsets for fixed header
        }, 1000);
        return false;
      }
    }
  });
  //Executed on page load with URL containing an anchor tag.
  if($(location.href.split("#")[1])) {
      var target = $('#'+location.href.split("#")[1]);
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offset height of header here too.
        }, 1000);
        return false;
      }
    }
});

点击这里查看实时实现。

如果您的锚是一个表元素或在一个表(行或单元格)中,上述方法就不能很好地工作。

我不得不使用javascript和绑定到窗口hashchange事件来解决这个问题(演示):

function moveUnderNav() {
    var $el, h = window.location.hash;
    if (h) {
        $el = $(h);
        if ($el.length && $el.closest('table').length) {
            $('body').scrollTop( $el.closest('table, tr').position().top - 26 );
        }
    }
}

$(window)
    .load(function () {
        moveUnderNav();
    })
    .on('hashchange', function () {
        moveUnderNav();
    });

*注意:hashchange事件并非在所有浏览器中都可用。

我在每个h1元素之前添加了40px-height .vspace元素。

<div class="vspace" id="gherkin"></div>
<div class="page-header">
  <h1>Gherkin</h1>
</div>

CSS中:

.vspace { height: 40px;}

它工作得很好,空间也没有堵塞。