首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >由于标题而导致scrollto偏移javascript的问题

由于标题而导致scrollto偏移javascript的问题
EN

Stack Overflow用户
提问于 2018-10-28 06:18:53
回答 2查看 90关注 0票数 2

我需要这个滚动到代码片段的帮助。问题是我需要为我的菜单设置一个偏移量。如果没有偏移量,我滚动到的标题将隐藏在菜单下面。你自己看看这里:https://julyfx.mystagingwebsite.com/stanford-mba-msx-essay-topic-analysis-examples/谁会碰巧有一个建议?谢谢!莉亚

代码语言:javascript
复制
<script type="text/javascript">
jQuery(document).ready(function($) {
   

$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });
});
</script>

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-28 07:50:57

应该是相对简单的:如果你的标题是85px高,你可以在你的代码中把这些85px加到偏移量上,所以这一行

代码语言:javascript
复制
scrollTop: target.offset().top

变成了

代码语言:javascript
复制
scrollTop: target.offset().top - 85

这样,窗口滚动的像素将比计算的小85px,因此该部分不会隐藏在标题后面。

票数 1
EN

Stack Overflow用户

发布于 2018-10-28 07:46:27

这只是一个建议,你有没有尝试过这样的东西:

代码语言:javascript
复制
window.scrollTo({top: (jQuery('#2').position().top-jQuery('header').height()), behavior: 'smooth' })

从上面的this.hash目标中提取#2会在哪里?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53026768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档