Jak przewijać stronę HTML do podanego anchora?

Chciałbym, aby przeglądarka przewijała stronę do danego anchora, po prostu za pomocą JavaScript.

W kodzie HTML podałem atrybut name lub id:

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

Lub

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

Chciałbym uzyskać taki sam efekt jak ty, przechodząc do http://server.com/path#anchorName. Stronę należy przewijać tak, aby Kotwica znajdowała się blisko góry widocznej części strony.

Author: Xufox, 2010-07-02

14 answers

function scrollTo(hash) {
    location.hash = "#" + hash;
}

Nie jQuery wymagane w ogóle!

 288
Author: Dean Harding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-02 06:25:24

Sposób prostszy:

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();
 189
Author: Armando Pérez Marqués,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-21 16:24:59

Możesz użyć jQuerys .animate(), .offset () i scrollTop. Jak

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

Przykładowy link: http://jsbin.com/unasi3/edit

Jeśli nie chcesz animować, użyj .scrollTop () like

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

Lub javascripts native location.hash Jak

location.hash = '#' + anchorid;
 118
Author: jAndy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-02 06:28:13

Świetne rozwiązanie autorstwa jAndy ' ego, ale płynne przewijanie wydaje się mieć problemy działające w Firefoksie.

Pisanie tego w ten sposób działa również w Firefoksie.

(function($) {
    $(document).ready(function() {
         $('html, body').animate({
           'scrollTop':   $('#anchorName2').offset().top
         }, 2000);
    });
})(jQuery);
 28
Author: 5hahiL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-07 11:11:59

Czyste rozwiązanie javascript bez JQuery. Testowane na Chrome i IE, nie testowane na 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;
  }
}

Demo: https://jsfiddle.net/jd7q25hg/12/

 22
Author: Michael Whinfrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-29 04:09:11
$(document).ready ->
  $("a[href^='#']").click ->
    $(document.body).animate
      scrollTop: $($(this).attr("href")).offset().top, 1000
 6
Author: cactis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-14 03:25:47

Większość odpowiedzi jest niepotrzebnie skomplikowana.

Jeśli chcesz po prostu przeskoczyć do elementu docelowego, nie potrzebujesz JavaScript:

# the link:
<a href="#target">Click here to jump.</a>

# target element:
<div id="target">Any kind of element.</div>

Jeśli chceszprzewiń do celu animowane , zapoznaj się z odpowiedzią @Shahil.

 5
Author: Brian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-10 17:49:20

Rozwiązanie z CSS-Tricks nie działa już w jQuery 2.2.0. Wyrzuci błąd selektora:

JavaScript runtime error: Syntax error, unrecognized expression: a [href*=#]: not ([href=#])

Naprawiłem to zmieniając selektor. Pełny fragment jest taki:

$(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;
    }
  }
 });
});
 5
Author: Bill Shihara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-23 19:33:47

W 2018 roku, nie potrzebujesz jQuery do czegoś prostego jak to. Wbudowana metoda [scrollIntoView()][1] obsługuje właściwość "behavior " do płynnego przewijania do dowolnego elementu na stronie. Możesz nawet zaktualizować adres URL przeglądarki za pomocą skrótu, aby można go było księgować.

Z Ten samouczek na temat przewijania zakładek HTML , Oto natywny sposób na automatyczne dodawanie płynnego przewijania do wszystkich linków anchor na twojej stronie:

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()
    })
}
 4
Author: coco puffs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-18 23:32:36

2018 Pure js:

Istnieje bardzo wygodny sposób przewijania do elementu:

el.scrollIntoView({
  behavior: 'smooth', // smooth scroll
  block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})

Ale o ile rozumiem, nie ma tak dobrego wsparcia, jak opcje poniżej.

Tutaj wpisz opis obrazka

Dowiedz się więcej o metodzie.


Jeśli jest to konieczne, aby element był na górze:

const element = document.querySelector('#element')
const top = element.getBoundingClientRect().top

window.scrollTo({
  top, // scroll so that the element is at the top of the view
  behavior: 'smooth' // smooth scroll
})

Przykład demonstracyjny na Codepen


Jeśli chcesz, aby element był w center:

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

Przykład demonstracyjny na Codepen


Wsparcie:

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

Piszą, że scroll jest tą samą metodą co scrollTo, ale wsparcie jest lepsze w scrollTo.

Więcej o metodzie

 2
Author: Илья Зеленько,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-02 16:13:56

Wiem, że to pytanie jest naprawdę stare, ale znalazłem łatwe i proste rozwiązanie jQuery w css-tricks . Tego właśnie używam.

$(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;
      }
    }
  });
});
 1
Author: Horacio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-06 20:26:07

Jest to działający skrypt, który przewija stronę do zakotwiczenia. Aby skonfigurować, po prostu podaj link kotwicy id, który pasuje do atrybutu name kotwicy, do której chcesz przewijać.

<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>
 0
Author: Rudy Lister,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-18 04:01:38

To działa:

$('.scroll').on("click", function(e) {

  e.preventDefault();

  var dest = $(this).attr("href");

  $("html, body").animate({

    'scrollTop':   $(dest).offset().top

  }, 2000);

});

Https://jsfiddle.net/68pnkfgd/

Po prostu dodaj klasę "scroll" do wszystkich linków, które chcesz animować

 0
Author: Chuck Le Butt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-02 13:09:42

jQuery("a[href^='#']").click(function(){
    jQuery('html, body').animate({
        scrollTop: jQuery( jQuery(this).attr('href') ).offset().top
    }, 1000);
    return false;
});
 0
Author: Adam Pery,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-17 11:40:39