Javascript 使用“平滑滚动”时,将截面居中

Javascript 使用“平滑滚动”时,将截面居中,javascript,jquery,html,anchor,smooth-scrolling,Javascript,Jquery,Html,Anchor,Smooth Scrolling,我正在使用克里斯·费迪南迪的平滑滚动脚本,我试图让它滚动到一个元素,但以该元素为中心着陆。类似于在 我尝试将以下代码添加到脚本的开头: $(document).ready(function(){ $('.downarrow a').click(elementhref = $('.downarrow a').attr('href')); var elementheight = $(elementhref).height(); var windowheight = $(w

我正在使用克里斯·费迪南迪的平滑滚动脚本,我试图让它滚动到一个元素,但以该元素为中心着陆。类似于在

我尝试将以下代码添加到脚本的开头:

$(document).ready(function(){

    $('.downarrow a').click(elementhref = $('.downarrow a').attr('href'));

    var elementheight = $(elementhref).height();
    var windowheight = $(window).height();

    if (elementheight < windowheight) {
        topoffset = ((windowheight / 2) - (elementheight / 2) - 30);
    } else {
        topoffset = 0;
    }

});
它对于第一个部分非常有效,但是当我单击下一个
。向下箭头a
元素时,我的代码只使用第一个部分的高度。但在我的HTML中,有几个链接与同一个类有关

这是我所拥有内容的简化版本:

<section id="home">
  <!--content-->
  <div class="downarrow"><a data-scroll href="#about">Scroll Down</a></div>
</section>

<section id="about">
  <!--content-->
  <div class="downarrow"><a data-scroll href="#portfolio">Scroll Down</a></div>
</section>

<section id="portfolio">
  <!--content-->
  <div class="downarrow"><a data-scroll href="#contact">Scroll Down</a></div>
</section>

<section id="contact">
  <!--content-->
</section>

我试图让它根据单击的元素更改
elementhref
变量,但这显然不适用于我的代码。我试着给每个
向下箭头
一个唯一的ID,但对我来说太复杂了

这是我第一次使用JavaScript和jQuery,所以我希望有一个我忽略的简单解决方案。

试试看

(function() {

   function setStuff(elementhref) {

      var elementheight = $(elementhref).height();
      var windowheight = $(window).height();

      if (elementheight < windowheight) {
        topoffset = ((windowheight / 2) - (elementheight / 2) - 30);
      } else {
       topoffset = 0;
      }

   }

   $('.downarrow a').click(function() {
     setStuff( $(this).attr('href') );
   });

})();
(函数(){
函数setStuff(elementhref){
var elementheight=$(elementhref).height();
var windowheight=$(window.height();
if(元素高度<窗口高度){
topoffset=((windowheight/2)-(elementheight/2)-30);
}否则{
topoffset=0;
}
}
$('.向下箭头a')。单击(函数(){
setStuff($(this.attr('href'));
});
})();
仅针对您“单击”的对象—
this
,并将其作为jquery对象,以便您可以访问jquery方法
$(this)



编辑/更新-在部分中添加了将单击处理程序与函数连接到
dostuff

*不知道您正在使用
topoffset
做什么,但希望能让您获得正确的
href
,然后在单击后设置
topoffset
。*在anon函数中包装
(函数(){…
当然是可选的
(function() {

   function setStuff(elementhref) {

      var elementheight = $(elementhref).height();
      var windowheight = $(window).height();

      if (elementheight < windowheight) {
        topoffset = ((windowheight / 2) - (elementheight / 2) - 30);
      } else {
       topoffset = 0;
      }

   }

   $('.downarrow a').click(function() {
     setStuff( $(this).attr('href') );
   });

})();