解决锚点跳转顶部被遮盖

通过js解决页内各种链接顶部被遮盖

主题顶部有固定导航栏或者像本主题一样宽屏模式下顶部有黑条,当网页内有锚点跳转的时候,由于默认目标锚点顶格到浏览器,会被导航条遮盖,由于锚点一般是header一般可以通过给header设定特定的css样式解决1

但是遇到段落内有脚注的锚点,就不行了,段落内文字不像header是单行的,如下图:

link被遮盖

所以只能还是js解决,添加一个listener,当遇到锚点点击的时候自动调整滚动栏,向下滚动一点。具体代码如下:

/**
 * Makes "skip to content" link work correctly in IE9, Chrome, and Opera
 * for better accessibility.
 *
 * @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/
 */
( function() {
  // 首先确定支持的浏览器IE9, Chrome, and Opera
  var isWebkit = navigator.userAgent.toLowerCase().indexOf( 'webkit' ) > -1,
    isOpera  = navigator.userAgent.toLowerCase().indexOf( 'opera' )  > -1,
    isIE     = navigator.userAgent.toLowerCase().indexOf( 'msie' )   > -1;

  if ( ( isWebkit || isOpera || isIE ) && document.getElementById && window.addEventListener ) {
    // 添加hashchange响应,当有锚点被点击的时候获取锚点id,获取的值有个#号所以substring一下
    window.addEventListener( 'hashchange', function() {
      var id = location.hash.substring( 1 ),
        element;
    //只选取特定字符的锚点添加,不符合的不添加
      if ( ! ( /^[A-z0-9:_-]+$/.test( id ) ) ) {
        return;
      }

      element = document.getElementById( id );

      if ( element ) {
        if ( ! ( /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) ) {
          element.tabIndex = -1;
        }

        element.focus();

        // 最终往下多高,根据你导航栏来调整
        window.scrollBy( 0, -53 );
      }
    }, {passive: true} );
  }
} )();

Leave a Reply

Your email address will not be published. Required fields are marked *