jQuery 滚动到锚点(减去设置的像素数)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11365091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:31:32  来源:igfitidea点击:

jQuery scroll to anchor (minus set amount of pixels)

jqueryscrollanchor

提问by John

I am using the following code to scroll to anchor points with jQuery:

我正在使用以下代码通过 jQuery 滚动到锚点:

$(document).ready(function() {
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
        });
      }
    }
  });

  // use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});

Is there anyway to make it scroll to that anchor but minus a set amount of pixels? (in my case i want it to go -92px)

有没有办法让它滚动到那个锚点但减去一定数量的像素?(在我的情况下,我希望它变为 -92px)

Thanks for any help.

谢谢你的帮助。

回答by Jonathan Savage

I just had to solve this problem myself. You need to adjust your offset by the amount of pixels you want to scrollTo. In my case, I needed it to be 50 pixels higher on the page. So, I subtracted 50 from targetOffset.

我只好自己解决这个问题。您需要根据要滚动到的像素量调整偏移量。就我而言,我需要它在页面上高出 50 像素。所以,我从 targetOffset 中减去了 50。

Now, the part of the code that's throwing a wobbly for you is location.hash - this is telling the browser to set its location to a specific point. In all cases, this is a string containing the ID you just scrolled to. So, it'd be something like '#foo'. You need to maintain this, so we'll leave it.

现在,为您抛出不稳定的代码部分是 location.hash - 这告诉浏览器将其位置设置为特定点。在所有情况下,这是一个包含您刚刚滚动到的 ID 的字符串。所以,它会像'#foo'。你需要维护它,所以我们会离开它。

However, to prevent the browser from 'jumping' when location.hash is set (a default browser action), you simply need to prevent the default action. So, pass your event 'e' through the completion function in the animate function. Then simply call e.preventDefault(). You'll have to make sure that the browser is actually calling an event, otherwise it will error out. So, an if-test fixes that.

但是,要防止浏览器在设置 location.hash 时“跳转”(默认浏览器操作),您只需阻止默认操作。因此,通过 animate 函数中的完成函数传递事件“e”。然后只需调用 e.preventDefault()。你必须确保浏览器实际上正在调用一个事件,否则它会出错。所以,如果测试解决了这个问题。

Done. Here's the revised code chunk:

完毕。这是修改后的代码块:

if (target) {
    var targetOffset = $target.offset().top - 50;
    $(this).click(function(event) {
      if(event != 'undefined') {
          event.preventDefault();}
      $(scrollElem).animate({scrollTop: targetOffset}, 400, function(e) {
          e.preventDefault();
          location.hash = target;
      });
    });
  }

回答by kaleazy

This is what I use:

这是我使用的:

function scrollToDiv(element){
    element = element.replace("link", "");
    $('html,body').unbind().animate({scrollTop: $(element).offset().top-50},'slow');
};

...where 50is the number of pixels to add/subtract.

...哪里50是要添加/减去的像素数。

回答by Max

This code work for me in any link anchor in my site respect "150px" height for fix menu on top.

此代码适用于我网站中的任何链接锚点,尊重“150px”高度以修复顶部的菜单。

<!-- SMOOTH SCROLL -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(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-150
        }, 1000);
        return false;
      }
    }
  });
});
</script>
<!-- End of SMOOTH SCROLL -->

回答by Никита Андрейчук

Lol)

哈哈)

<span class="anchor" id="section1"></span>
<div class="section"></div>

<span class="anchor" id="section2"></span>
<div class="section"></div>

<span class="anchor" id="section3"></span>
<div class="section"></div>

<style>
.anchor{
  display: block;
  height: 115px; /*same height as header*/
  margin-top: -115px; /*same height as header*/
  visibility: hidden;
}
</style>

回答by Garrick Crouch

This is a jQuery snippet i use and find very resourceful & flexible. You can remove the DOM Ready if you run it in the footer which is suggested. Just load any post 1.4v library ahead of it. It listens for all clicks on anchors, then it runs a boolean and an OR for class checks. If it finds a class then it runs through the script and animation. You can adjust your offset from its ending position i prefer 60px on most applications but feel free to adjust as need be.

这是我使用的一个 jQuery 片段,并且发现它非常足智多谋和灵活。如果您在建议的页脚中运行它,您可以删除 DOM Ready。只需在它之前加载任何后 1.4v 库。它侦听对锚点的所有点击,然后运行一个布尔值和一个 OR 进行类检查。如果它找到一个类,那么它会运行脚本和动画。您可以从其结束位置调整偏移量,在大多数应用程序中我更喜欢 60px,但可以根据需要随意调整。

<!--jQuerySmoothScroll-->
<script>
jQuery(document).ready(function(){
   // Add smooth scrolling to all links
   jQuery("a").on('click', function(event) {
      //check that we have the smooth-scroll class add as many as need be
            if (jQuery(this).hasClass("whatever-class-you-want") || jQuery(this).hasClass("smooth-scroll")) {
       // Make sure this.hash has a value before overriding default behavior
         if (this.hash !== "") {
           // Prevent default anchor click behavior
          event.preventDefault();
         // Store hash
         var hash = this.hash;
        // Using jQuery's animate() method to add smooth page scroll
        // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
        jQuery('html, body').animate({
        scrollTop: jQuery(hash).offset().top-60// Set offset from top position
       }, 800, function(){
   
        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
     } // End if
    } // End if (class)
  });
});
</script>

回答by vibrationbaby

I was unable to use Jonathan Savage's solution as I couldn't pass an event callback into animate() without error. I had this issue today and found a simple solution:

我无法使用 Jonathan Savage 的解决方案,因为我无法毫无错误地将事件回调传递给 animate()。我今天遇到了这个问题,并找到了一个简单的解决方案:

      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top - 92;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = targetOffset;
          });
        });

Subtract your pixel offset from the targetOffset variable, then assign location.hash to that variable. Stops the page jumping when scrolling to the target hash.

从 targetOffset 变量中减去您的像素偏移,然后将 location.hash 分配给该变量。滚动到目标哈希时停止页面跳转。

回答by Jeremy Morgan

This is a jQuery implementation which I use that was based on Никита Андрейчук's solution. The pixel adjustment variable can be set dynamically this way, though it is hard coded in this example.

这是我使用的 jQuery 实现,它基于 Никита Андрейчук 的解决方案。像素调整变量可以通过这种方式动态设置,尽管在本示例中是硬编码的。

$( 'a' ).each(function() {
    var pixels = 145;
    var name = $( this ).attr( 'name' );
    if ( typeof name != 'undefined' ) {
        $( this ).css({
          'display'    : 'block',
          'height'     : pixels + 'px',
          'margin-top' : '-' + pixels + 'px',
          'visibility' : 'hidden'
        });
    }
});

回答by cdrck

Here is what i use. Set the offset to what you need.

这是我使用的。将偏移量设置为您需要的值。

$('a[href^="#"]').click(function(e) {
  e.preventDefault();
  $(window).stop(true).scrollTo(this.hash {duration:1000,interrupt:true,offset: -50});
});

回答by nick

Not wanting to learn Javascript and always looking for the easiest option, just create an empty DIV above the anchor point you want to land at then in CSS make the div

不想学习 Javascript 并且总是在寻找最简单的选择,只需在要着陆的锚点上方创建一个空的 DIV,然后在 CSS 中创建 div

anchorpointl{margin-top: -115px;}

anchorpointl{margin-top: -115px;}

or however far above or below you want to go and the jobs done

或者无论远高于或低于你想要去和完成的工作