代码之家  ›  专栏  ›  技术社区  ›  Juha Syrjälä

如何将HTML页面滚动到给定的锚?

  •  214
  • Juha Syrjälä  · 技术社区  · 14 年前

    我想让浏览器滚动页面到一个给定的锚,只是通过使用JavaScript。

    我指定了一个 name id

     <a name="anchorName">..</a>
    

     <h1 id="anchorName2">..</h1>
    

    http://server.com/path#anchorName

    15 回复  |  直到 7 年前
        1
  •  370
  •   Dean Harding    14 年前
    function scrollTo(hash) {
        location.hash = "#" + hash;
    }
    

    根本不需要jQuery!

        2
  •  242
  •   Armando Pérez Marqués    9 年前

    更简单:

    var element_to_scroll_to = document.getElementById('anchorName2');
    // Or:
    var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
    // Or:
    var element_to_scroll_to = $('.my-element-class')[0];
    // Basically `element_to_scroll_to` just have to be a reference
    // to any DOM element present on the page
    // Then:
    element_to_scroll_to.scrollIntoView();
    
        3
  •  125
  •   jAndy    14 年前

    你可以用jQuerys .animate() , .offset() scrollTop

    $(document.body).animate({
        'scrollTop':   $('#anchorName2').offset().top
    }, 2000);
    

    链接示例: http://jsbin.com/unasi3/edit

    如果不想设置动画,请使用 .scrollTop()

    $(document.body).scrollTop($('#anchorName2').offset().top);
    

    location.hash 喜欢

    location.hash = '#' + anchorid;
    
        4
  •  51
  •   gaborous    4 年前

    2018-2020纯js:

    有一种非常方便的方法可以滚动到元素:

    el.scrollingto视图({
    block:'start'//元素的上边框将在可滚动区域窗口可见部分的顶部对齐。
    })
    

    了解有关该方法的更多信息

    如果有必要使元件位于顶部:

    const element=document.querySelector('#element')
    const topPos=element.getBoundingClientRect().top+window.pageYOffset
    
    窗口.scrollTo({
    top:topPos,//滚动以使元素位于视图的顶部
    })
    

    代码笔演示示例


    如果希望元素位于中心:

    const element=document.querySelector('#element')
    const viewHeight=Math.max(document.documentElement.clientHeight,window.innerHeight | | 0);
    
    顶部:rect.top+rect.height/2-viewHeight/2,
    behavior:'smooth'//平滑滚动
    });
    
    

    代码笔演示示例


    支持:

    他们写道,scrollscrollTo的方法相同,但在scrollTo中支持效果更好

    有关方法的更多信息

    enter image description here

    Learn more about the method.


    如果有必要使元件位于顶部:

    const element = document.querySelector('#element')
    const topPos = element.getBoundingClientRect().top + window.pageYOffset
    
    window.scrollTo({
      top: topPos, // scroll so that the element is at the top of the view
      behavior: 'smooth' // smooth scroll
    })
    

    Demonstration example on Codepen


    如果希望元素位于中心:

    const element = document.querySelector('#element')
    const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
    const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    
    window.scroll({
      top: rect.top + rect.height / 2 - viewHeight / 2,
      behavior: 'smooth' // smooth scroll
    });
    

    Demonstration example on Codepen


    支持:

    введите сюда описание изображения

    scroll方法与scrollTo,但支持率在滚动到.

    More about the method

        5
  •  35
  •   5hahiL    12 年前

    在Firefox中也是这样写的。

    (function($) {
        $(document).ready(function() {
             $('html, body').animate({
               'scrollTop':   $('#anchorName2').offset().top
             }, 2000);
        });
    })(jQuery);
    
        6
  •  29
  •   Michael Whinfrey    8 年前

    没有JQuery的纯javascript解决方案。在铬上测试;也就是说,没有在IOS上测试

    function ScrollTo(name) {
      ScrollToResolver(document.getElementById(name));
    }
    
    function ScrollToResolver(elem) {
      var jump = parseInt(elem.getBoundingClientRect().top * .2);
      document.body.scrollTop += jump;
      document.documentElement.scrollTop += jump;
      if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
        elem.lastjump = Math.abs(jump);
        setTimeout(function() { ScrollToResolver(elem);}, "100");
      } else {
        elem.lastjump = null;
      }
    }
    

    演示: https://jsfiddle.net/jd7q25hg/12/

        7
  •  26
  •   Aadit M Shah    4 年前

    scrollIntoView() 方法支持“ behavior

    this tutorial on scrolling HTML Bookmarks

    let anchorlinks = document.querySelectorAll('a[href^="#"]')
     
    for (let item of anchorlinks) { // relitere 
        item.addEventListener('click', (e)=> {
            let hashval = item.getAttribute('href')
            let target = document.querySelector(hashval)
            target.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            })
            history.pushState(null, null, hashval)
            e.preventDefault()
        })
    }
    
        8
  •  15
  •   Arseniy-II    3 年前

    平滑滚动到正确位置(2020)

    得到 y 协调和使用 window.scrollTo({top: y, behavior: 'smooth'})

    const id = 'anchorName2';
    const yourElement = document.getElementById(id);
    const y = yourElement.getBoundingClientRect().top + window.pageYOffset;
    
    window.scrollTo({top: y, behavior: 'smooth'});
    
        9
  •  8
  •   eslam elameen    4 年前

    要使浏览器将页面滚动到给定的锚点,最简单的方法是键入style.css*{scroll behavior:smooth;} 在html导航中使用#节名

    *{scroll-behavior: smooth;}
    <a href="#scroll-to">Home<a/>
    
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    <p>other sections</p>
    
    <section id="scroll-to">
    <p>it will scroll down to this section</p>
    </section>
        10
  •  5
  •   cactis    13 年前
    $(document).ready ->
      $("a[href^='#']").click ->
        $(document.body).animate
          scrollTop: $($(this).attr("href")).offset().top, 1000
    
        11
  •  5
  •   dakab    8 年前

    CSS技巧的解决方案在jquery2.2.0中不再有效。它将抛出一个选择器错误:

    JavaScript运行时错误:语法错误,无法识别的表达式:a[href*=#]:not([href=#])

    我通过改变选择器来修复它。完整片段如下:

    $(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
          }, 1000);
          return false;
        }
      }
     });
    });
    
        12
  •  4
  •   Chuck Le Butt    6 年前

    这样做有效:

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

    https://jsfiddle.net/68pnkfgd/

    只需添加类'滚动'到任何链接,你想动画

        13
  •  3
  •   Mr.Lister    7 年前

    这是一个工作脚本,将滚动到锚页。

    <script>
    jQuery(document).ready(function ($){ 
     $('a').click(function (){ 
      var id = $(this).attr('id');
      console.log(id);
      if ( id == 'cet' || id == 'protein' ) {
       $('html, body').animate({ scrollTop: $('[name="' + id + '"]').offset().top}, 'slow'); 
      }
     }); 
    });
    </script>
    
        14
  •  3
  •   Adam Pery    6 年前

    jQuery("a[href^='#']").click(function(){
        jQuery('html, body').animate({
            scrollTop: jQuery( jQuery(this).attr('href') ).offset().top
        }, 1000);
        return false;
    });
        15
  •  2
  •   5260452    8 年前

    大多数答案都过于复杂。

    对于目标元素,您不需要JavaScript:

    # the link:
    <a href="#target">Click here to jump.</a>
    
    # target element:
    <div id="target">Any kind of element.</div>
    

    如果你想的话 ,请参考@Shahil的答案。

        16
  •  1
  •   Horacio    10 年前

    我知道这个问题已经很老了,但我在中找到了一个简单易懂的jQuery解决方案 css-tricks . 我现在用的就是这个。

    $(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
            }, 1000);
            return false;
          }
        }
      });
    });
    
        17
  •  1
  •   Yordan Georgiev    6 年前

    vue2解决方案。。。添加简单数据属性以强制更新

      const app = new Vue({ 
      ... 
    
      , updated: function() {
               this.$nextTick(function() {
               var uri = window.location.href
               var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
               if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
                  this.updater = "" // only on page-load !
                  location.href = "#"+String(anchor)
               }
             })
            }
         });
         app.updater = "page_load"
    
     /* smooth scrolling in css - works in html5 only */
     html, body {
         scroll-behavior: smooth;
     }