繁体   English   中英

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

[英]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()

在顶部留出一点空间...


或者,您可以执行类似操作( 不确定,需要进行测试 ):

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) 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM