使用平滑的滚动片段,页面中的中心元素

Using a smooth scroll snippet, center element in page

我正在使用这个脚本。

$(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
        }, 1000);
        return false;
      }
    }
  });
});

除一件事外,它运行良好。当我单击锚点并向下滚动时,一半的文本被截断了。我想做一个偏移量什么的,所以在文本上方的屏幕顶部有一点空白,像这样:

目前,它看起来像这样:

试试这样的东西:

scrollTop: target.offset().top - target.height()

在顶部放一点 space...


或者你可以这样做(不确定,需要测试):

var video = target.next() // considering that is the video block
var centerizeHeight = $(window).height() - (target.height() + video.height()) 
centerizeHeight = (centerizeHeight > 0) centerizeHeight : 1
//...
scrollTop: target.offset().top - (centerizeHeight/2) 

注意:确保您的文档类型在您的页面中