Smart Header for Zhihu

根据页面滚动,自动隐藏及显示知乎顶栏。

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name        Smart Header for Zhihu
// @namespace   org.sorz.lab.zhihu
// @include     http://www.zhihu.com/*
// @version     0.2
// @grant       none
// @description 根据页面滚动,自动隐藏及显示知乎顶栏。
// ==/UserScript==

$(document).ready(function() {
  var $header = $('.zu-top');
  var headerHeight = $header.outerHeight() + 3;
  
  var refPos = $(document).scrollTop();
  var headerPos = 0;
  
  function isHidden() {
    return headerPos <= -headerHeight;
  }
  
  function isShown() {
    return headerPos >= 0;
  }
  
  $(window).scroll(function() {
    var scroll = $(document).scrollTop() - refPos;
    if (Math.abs(scroll) > headerHeight) {
      var oldHeaderPos = headerPos;
      headerPos = scroll > 0 ? -headerHeight : 0;
      if (headerPos != oldHeaderPos)
        $header.animate({top: headerPos + 'px'}, 200);
      refPos = $(document).scrollTop();
      return;
    }
    
    if ((scroll > 0 && !isHidden()) || (scroll < 0 && !isShown())) {
      headerPos = scroll > 0 ? -scroll : -headerHeight - scroll;
      $header.css('top', headerPos + 'px');
    } else {
      refPos = $(document).scrollTop();
    }
  });
});