【问题标题】:jQuery scroll to anchor (minus set amount of pixels)jQuery滚动到锚点(减去设置的像素数量)
【发布时间】:2012-07-07 01:59:32
【问题描述】:

我正在使用以下代码通过 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 [];
  }

});

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

感谢您的帮助。

【问题讨论】:

  • 它们有何相似之处?我的是通过 jquery 滚动到每个锚点,当它们靠近页面顶部时,您链接到的内容想要滚动。代码非常不同。
  • 唯一的区别是你想滚动到哪个选择器,以及偏移量。查看接受的答案并将#id替换为您想要的选择器,并将100替换为您想要的偏移量。

标签: jquery scroll anchor


【解决方案1】:

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

现在,给您带来不稳定的代码部分是 location.hash - 它告诉浏览器将其位置设置为特定点。在所有情况下,这是一个包含您刚刚滚动到的 ID 的字符串。所以,它会是类似“#foo”的东西。你需要维护它,所以我们会留下它。

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

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

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;
      });
    });
  }

【讨论】:

  • 对不起,我知道这是一个老问题,但是:动画回调没有收到任何参数(参见api.jquery.com/animate),所以 e.preventDefault() 失败。这在过去 2 年有变化吗?是否有最新的方法来防止 location.hash = target 的默认行为?
  • Andreyu,看看stackoverflow.com/questions/1489624/…Borgar 的回答
【解决方案2】:

这是我用的:

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

...其中50 是要添加/减去的像素数。

【讨论】:

  • 谢谢!正是我需要的!
【解决方案3】:

此代码适用于我网站的任何链接锚点,高度为“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 -->

【讨论】:

    【解决方案4】:

    <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>

    【讨论】:

    • 这很好用,但你必须知道它可能会覆盖锚点上方 115px 中的链接、按钮或任何其他交互元素,你将无法点击它们。 .
    【解决方案5】:

    我无法使用 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;
              });
            });
    

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

    【讨论】:

      【解决方案6】:

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

      <!--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>

      【讨论】:

        【解决方案7】:

        这是我使用的基于 Никита Андрейчук 解决方案的 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'
                });
            }
        });
        

        【讨论】:

          【解决方案8】:

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

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

          【讨论】:

            【解决方案9】:

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

            anchorpointl{margin-top: -115px;}

            或者无论你想去多远或多远,工作完成

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2023-03-20
              • 2016-10-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多