HTML位置:固定的可变高度页眉和页内锚点

时间:2016-03-17 16:24:43

标签: html css anchor

我已经成功设计了页面锚点,首次点击会补偿固定的页眉高度,代码如下:

<p id="anchorid" style="padding-top: 287px; margin-top: -287px; width: 20px;">
   FILLER TEXT
</p>

我遇到的问题是当你滚动时我的标题会缩小,所以一旦你通过一个锚点击一个页面,下次你在该页面上点击一个锚页面时,填充 - 补偿(因为它设置为初始标题高度)并且该部分被带到页面的中间而不是顶部。我希望做的是将锚点填充动态设置为标题的高度,以便它始终将该部分置于顶部,但我遗憾地失去了如何执行此操作。

有没有办法使用锚点(id =&#34;填充物&#34;)让浏览器滚动到某个点,具体取决于标题的高度,使用CSS?

此处解决了类似的问题,但其标题并未改变大小:HTML position:fixed page header and in-page anchors

1 个答案:

答案 0 :(得分:2)

编辑回答:

以下是我用于修复标题的代码,该标题在使用jQuery滚动到使用smouth滚动进行锚定时处理偏移。

以下是插图:https://jsfiddle.net/mmb5k7xb/1/

要查看脚本如何以不同的高度做出反应,只需更改html部分中菜单高度的值即可。

希望它有所帮助。

<script type="text/javascript">
var $ = jQuery.noConflict();
$(document).ready(function($) {

var menu_height = $('.menu').height(); // calulate the height of the menu

(function(document, history, location) {
  var HISTORY_SUPPORT = !!(history && history.pushState);

  var anchorScrolls = {
    ANCHOR_REGEX: /^#[^ ]+$/,
    OFFSET_HEIGHT_PX: menu_height, // Set the offset with the dynamic value

    /**
     * Establish events, and fix initial scroll position if a hash is provided.
     */
    init: function() {
      this.scrollIfAnchor(location.hash);
      $('body').on('click', 'a', $.proxy(this, 'delegateAnchors'));
    },

    /**
     * Return the offset amount to deduct from the normal scroll position.
     * Modify as appropriate to allow for dynamic calculations
     */
    getFixedOffset: function() {
      return this.OFFSET_HEIGHT_PX;
    },

    /**
     * If the provided href is an anchor which resolves to an element on the
     * page, scroll to it.
     * @param  {String} href
     * @return {Boolean} - Was the href an anchor.
     */
    scrollIfAnchor: function(href, pushToHistory) {
      var match, anchorOffset;

      if(!this.ANCHOR_REGEX.test(href)) {
        return false;
      }

      match = document.getElementById(href.slice(1));

      if(match) {
        anchorOffset = $(match).offset().top - this.getFixedOffset();
        $('html, body').animate({ scrollTop: anchorOffset});

        // Add the state to history as-per normal anchor links
        if(HISTORY_SUPPORT && pushToHistory) {
          history.pushState({}, document.title, location.pathname + href);
        }
      }

      return !!match;
    },

    /**
     * If the click event's target was an anchor, fix the scroll position.
     */
    delegateAnchors: function(e) {
      var elem = e.target;

      if(this.scrollIfAnchor(elem.getAttribute('href'), true)) {
        e.preventDefault();
      }
    }
  };

    $(document).ready($.proxy(anchorScrolls, 'init'));
})(window.document, window.history, window.location);
});
</script>