【问题标题】:Smooth scroll to div id jQuery平滑滚动到 div id jQuery
【发布时间】:2013-10-01 11:48:52
【问题描述】:

我一直试图让滚动到 div id jquery 代码正常工作。基于另一个堆栈溢出问题,我尝试了以下

演示http://jsfiddle.net/kevinPHPkevin/8tLdq/

$('#myButton').click(function() {
   $.scrollTo($('#myDiv'), 1000);
});

但它没有用。它只是捕捉到 div。我也试过了

$('#myButton').click(function(event) {
     event.preventDefault();
   $.scrollTo($('#myDiv'), 1000);
});

没有进展。

【问题讨论】:

标签: javascript jquery scroll


【解决方案1】:

您需要为html, body 设置动画

演示http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

【讨论】:

  • @vector 我有一个问题,一旦点击它,我必须与 jquery 对抗才能向上滚动,有什么解决方案吗?
  • @yesitsme ...在我的情况下向上或向下
  • @GraySpectrum up,刚刚点击,听起来好像有延迟。
  • 我有同样的问题,如果我有几个按钮需要滚动到不同的位置,尝试修改此代码但它不起作用。你能再举一个例子吗?
  • 为它找到了一些“修复”。 proper element 的滚动现在是固定的,但仍然可以通过单击相同的“滚动到”目标上下移动:var target = $(this).data("target"); $(".basics-content").animate({scrollTop: $(target).offset().top}, 1000); }); 说明:.basics-content 是模态的内部 div,它我实际上想滚动到 target 我提供元素的 id 号 ...
【解决方案2】:

如果您想覆盖页面上的标准 href-id 导航,而不更改 平滑滚动 的 HTML 标记,请使用此 (example):

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});

【讨论】:

  • 这很好用,我可以建议一个很小的调整var pos = $(id).offset().top; 可以是var pos = $id.offset().top;
  • 非常好。如果您只想在某些链接上发生这种情况(例如您有一些要显示或隐藏的信息),只需向它们添加一个类名并将您的类名(例如滚动条)添加到匹配声明的末尾(例如 a[href ^="#"].scroller).
  • 没有 jQuery 怎么办?
【解决方案3】:

这是我的 2 美分:

Javascript:

$('.scroll').click(function() {
    $('body').animate({
        scrollTop: eval($('#' + $(this).attr('target')).offset().top - 70)
    }, 1000);
});

HTML:

<a class="scroll" target="contact">Contact</a>

和目标:

<h2 id="contact">Contact</h2>

【讨论】:

  • 只有在你不声明 doctype 的情况下这个接缝才起作用。
  • 这里eval有什么用?
  • 我认为滚动需要$('html, body').animate
【解决方案4】:

纯 JS:

如果你使用现代浏览器,可以在纯 JS 中完成。

document
    .getElementById("range-calculator")
    .scrollIntoView({ behavior: "smooth" });

浏览器支持有点问题,但是modern browsers support it

【讨论】:

  • iOS 上的 Safari 不支持此功能
  • 通常的嫌疑人。桌面上的 Safari 也不支持它(根据 MDN)
  • 我刚刚尝试了 safari 桌面,现在可以工作了。
【解决方案5】:

再举一个例子:

HTML 链接:

<a href="#featured" class="scrollTo">Learn More</a>

JS:

  $(".scrollTo").on('click', function(e) {
     e.preventDefault();
     var target = $(this).attr('href');
     $('html, body').animate({
       scrollTop: ($(target).offset().top)
     }, 2000);
  });

HTML 锚点:

  <div id="featured">My content here</div>

【讨论】:

  • 之前它没有滚动到 div 的顶部,但后来我做了下面提到的更改并且它起作用了。 scrollTop: ($(target).offset().top - 120)
【解决方案6】:

这是我使用的:

<!-- jquery smooth scroll to id's -->   
<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
        }, 500);
        return false;
      }
    }
  });
});
</script>

这个的美妙之处在于您可以使用无限数量的哈希链接和相应的 id,而不必为每个都执行新的脚本。

如果您使用的是 WordPress,请将代码插入主题的 footer.php 文件中,就在结束正文标记 &lt;/body&gt; 之前。

如果您无权访问主题文件,您可以将代码嵌入帖子/页面编辑器(您必须在文本模式下编辑帖子)或将加载到所有页面的文本小部件中。

如果您使用任何其他 CMS 或仅使用 HTML,您可以在结束正文标记 &lt;/body&gt; 之前在所有页面上加载的部分中插入代码。

如果您需要更多详细信息,请在此处查看我的快速帖子:jQuery smooth scroll to id

希望对您有所帮助,如果您对此有任何疑问,请告诉我。

【讨论】:

  • 爱这多么简单和香草,完美。
【解决方案7】:

此代码对于网络上的任何内部链接都很有用

    $("[href^='#']").click(function() {
        id=$(this).attr("href")
        $('html, body').animate({
            scrollTop: $(id).offset().top
        }, 2000);
    });

【讨论】:

    【解决方案8】:

    您确定要加载 jQuery scrollTo 插件文件吗?

    您可能会在控制台中收到 object: method not found "scrollTo" 错误。

    scrollTO 方法不是原生 jquery 方法。要使用它,您需要包含 jquery 滚动到插件文件。

    参考: http://flesler.blogspot.in/2009/05/jqueryscrollto-142-released.html http://flesler.blogspot.in/2007/10/jqueryscrollto.html

    解决方案: 将其添加到头部。

    <script src="\\path\to\the\jquery.scrollTo.js file"></script>
    

    【讨论】:

    • 这应该是公认的答案。问题中的代码是正确的,并且工作正常。看起来好像 scrollTo 插件没有/没有工作。 . .他没有询问做类似事情的不同方法。
    【解决方案9】:

    我对 Vanilla JS 和 jQuery 的解决方案

    原版 JS:

    document
        .querySelector("#myDiv")
        .scrollIntoView({ behavior: "smooth" });
    

    jQuery:

    您需要为 html、body 设置动画

    $("#myButton").click(function() {
        $('html, body').animate({
            scrollTop: $("#myDiv").offset().top
        }, 2000);
    });
    

    【讨论】:

      【解决方案10】:

      此脚本是对 Vector 脚本的改进。我对它做了一点改动。因此,此脚本适用于其中包含 page-scroll 类的每个链接。

      一开始没有缓动:

      $("a.page-scroll").click(function() {
          var targetDiv = $(this).attr('href');
          $('html, body').animate({
              scrollTop: $(targetDiv).offset().top
          }, 1000);
      });
      

      为了缓和你需要 Jquery UI:

      <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
      

      将此添加到脚本中:

      'easeOutExpo'
      

      决赛

      $("a.page-scroll").click(function() {
          var targetDiv = $(this).attr('href');
          $('html, body').animate({
              scrollTop: $(targetDiv).offset().top
          }, 1000, 'easeOutExpo');
      });
      

      你可以在这里找到所有的缓动:Cheat Sheet

      【讨论】:

        【解决方案11】:

        这个是最简单的。来源-https://www.w3schools.com/jsref/met_element_scrollintoview.asp

        var elmnt = document.getElementById("content");
        elmnt.scrollIntoView();
        

        【讨论】:

          【解决方案12】:

          这是我使用 jQuery 平滑滚动到 div / 锚点的解决方案,以防你有一个固定的标题,这样它就不会在它下面滚动。 如果您从其他页面链接它也可以使用。

          只需将“.site-header”替换为包含您的标题的 div。

          $(function() {
          
          $('a[href*="#"]:not([href="#"])').click(function() {
          var headerheight = $(".site-header").outerHeight();
          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 - headerheight)
              }, 1000);
              return false;
            }
          }
          });
          
          //Executed on page load with URL containing an anchor tag.
          if($(location.href.split("#")[1])) {
          var headerheight = $(".site-header").outerHeight();
            var target = $('#'+location.href.split("#")[1]);
            if (target.length) {
              $('html,body').animate({
                scrollTop: target.offset().top - headerheight
              }, 1);
              return false;
            }
          }
          });
          

          【讨论】:

            【解决方案13】:

            您可以使用以下简单的 jQuery 代码来完成。

            可以从这里找到教程、演示和源代码 - Smooth scroll to div using jQuery

            JavaScript:

            $(function() {
                $('a[href*=#]:not([href=#])').click(function() {
                    var target = $(this.hash);
                    target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
                    if (target.length) {
                        $('html,body').animate({
                          scrollTop: target.offset().top
                        }, 1000);
                        return false;
                    }
                });
            });
            

            HTML:

            <a href="#section1">Go Section 1</a>
            <div id="section1">
                <!-- Content goes here -->
            </div>
            

            【讨论】:

              【解决方案14】:

              我在这里尝试过,对我来说效果很好。

              $('a[href*="#"]').on('click', function (e) {
                  e.preventDefault();
              
                  $('html, body').animate({
                      scrollTop: $($(this).attr('href')).offset().top
                  }, 500, 'linear');
              });
              

              HTML:

               <a href="#fast-food" class="active" data-toggle="tab" >FAST FOOD</a>
              
              <div id="fast-food">
              <p> Scroll Here... </p>
                </div>
              

              【讨论】:

              • 你的回答有什么不同?
              【解决方案15】:

              这对我有用。

              <div id="demo">
                      <h2>Demo</h2>
              </div>
              <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
              <script>
                  $(document).ready(function () {
                      // Handler for .ready() called.
                      $('html, body').animate({
                          scrollTop: $('#demo').offset().top
                      }, 'slow');
                  });
              </script>
              

              谢谢。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2023-03-23
                • 1970-01-01
                • 1970-01-01
                • 2014-07-12
                • 1970-01-01
                • 2012-05-20
                • 1970-01-01
                相关资源
                最近更新 更多