簡體   English   中英

如何使用Javascript進行平滑滾動來調整偏移位置?

[英]How can I adjust the offset position using Javascript for a smoth scroll?

如何調整必須滾動到錨點但還要包含偏移量的javascript。 我添加了200px偏移量的規則,但沒有任何效果。

                $('a[href*="#"]')
              .not('[href="#"]')
              .not('[href="#0"]')
              .click(function(event) {
                // On-page links
                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) {
                    event.preventDefault();
                    $('html, body').animate({
                      scrollTop: target.offset().top - 200;
                    }, 1000, function() {
                      var $target = $(target);
                      $target.focus();
                      if ($target.is(":focus")) {
                        return false;
                      } else {
                        $target.attr('tabindex','-1');
                        $target.focus();
                      };
                    });
                  }
                }
            });

在下面的代碼段中查看使用jquery的簡單示例。

 $('a').click(function(evt) { evt.preventDefault(); $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top - 50 }, 800, function() {}); }); 
 .empty { height: 500px; width: 100%; background: #ccc; } #content { height: 200px; width: 100%; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#content">Click Me!</a> <div class="empty"></div> <div id="content"> Content goes here.! </div> <div class="empty"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM