Hoe omhoog of omlaag scrollen op de pagina naar een anker met jQuery?

Ik ben op zoek naar een manier om een dia-effect toe te voegen voor wanneer u op een link naar een lokaal anker bovenaan of onderaan de pagina klikt.

Ik zou graag iets willen waar je een link als volgt hebt:

<a href="#nameofdivetc">link text, img etc.</a>

misschien met een klasse toegevoegd zodat je weet dat je wilt dat deze link een glijdende link is:

<a href="#nameofdivetc" class="sliding-link">link text, img etc.</a>

Als er vervolgens op deze link wordt geklikt, schuift de pagina omhoog of omlaag naar de gewenste plaats (kan een div, kop, bovenkant van de pagina zijn, enz.).


Dit is wat ik eerder had:

   $(document).ready(function(){
    $(".scroll").click(function(event){
        //prevent the default action for the click event
        event.preventDefault();
        //get the full url - like mysitecom/index.htm#home
        var full_url = this.href;
        //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
        var parts = full_url.split("#");
        var trgt = parts[1];
        //get the top offset of the target anchor
        var target_offset = $("#"+trgt).offset();
        var target_top = target_offset.top;
        //goto that anchor by setting the body scroll top to anchor top
        $('html, body').animate({scrollTop:target_top}, 1500, 'easeInSine');
    });
});

Antwoord 1, autoriteit 100%

Beschrijving

U kunt dit doen met jQuery.offset()en jQuery.animate().

Bekijk de jsFiddle-demonstratie.

Voorbeeld

function scrollToAnchor(aid){
    var aTag = $("a[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}
scrollToAnchor('id3');

Meer informatie


Antwoord 2, autoriteit 9%

Ervan uitgaande dat uw href-kenmerk linkt naar een divmet de tag idmet dezelfde naam (zoals gewoonlijk), kunt u deze code:

HTML

<a href="#goto" class="sliding-link">Link to div</a>
<div id="goto">I'm the div</div>

JAVASCRIPT – (Jquery)

$(".sliding-link").click(function(e) {
    e.preventDefault();
    var aid = $(this).attr("href");
    $('html,body').animate({scrollTop: $(aid).offset().top},'slow');
});

Antwoord 3, autoriteit 2%

function scroll_to_anchor(anchor_id){
    var tag = $("#"+anchor_id+"");
    $('html,body').animate({scrollTop: tag.offset().top},'slow');
}

Antwoord 4, autoriteit 2%

Dit maakte mijn leven zoveel gemakkelijker. Je plaatst in feite je elementen-ID-tag en de scrolls ernaartoe zonder veel code

http://balupton.github.io/jQuery-scrollto/

in javascript

$('#scrollto1').ScrollTo();

In uw HTML

<div id="scroollto1">

Hier ben ik helemaal naar beneden op de pagina


Antwoord 5

U moet ook van mening zijn dat het doelwit een opvulling heeft en dus positiongebruiken in plaats van offset. U kunt ook rekening houden met een potentiële NAV-balk die u het doelwit niet wilt overlappen.

const $navbar = $('.navbar');
$('a[href^="#"]').on('click', function(e) {
    e.preventDefault();
    const scrollTop =
        $($(this).attr('href')).position().top -
        $navbar.outerHeight();
    $('html, body').animate({ scrollTop });
})

Antwoord 6

Mijn aanpak met jQuery om gewoon alle ingesloten ankerlinks-dia te maken in plaats van onmiddellijk te springen

Het is echt vergelijkbaar met het antwoord door Santi Nunez , maar het is meer betrouwbaar .

Ondersteuning

  • Multi-framework-omgeving.
  • Voordat de pagina is voltooid.
<a href="#myid">Go to</a>
<div id="myid"></div>
// Slow scroll with anchors
(function($){
    $(document).on('click', 'a[href^=#]', function(e){
        e.preventDefault();
        var id = $(this).attr('href');
        $('html,body').animate({scrollTop: $(id).offset().top}, 500);
    });
})(jQuery);

Antwoord 7

Hier is de oplossing die voor mij werkte. Dit is een algemene functie die werkt voor alle a-tags die verwijzen naar een naam a

$("a[href^=#]").on('click', function(event) { 
    event.preventDefault(); 
    var name = $(this).attr('href'); 
    var target = $('a[name="' + name.substring(1) + '"]'); 
    $('html,body').animate({ scrollTop: $(target).offset().top }, 'slow'); 
});

Opmerking 1: Zorg ervoor dat u dubbele aanhalingstekens "gebruikt in uw html. Als u enkele aanhalingstekens gebruikt, wijzigt u het bovenstaande deel van de code in var target = $("a[name='" + name.substring(1) + "']");

Opmerking 2: In sommige gevallen, vooral wanneer u de plakbalk van de bootstrap gebruikt, wordt de naam averborgen onder de navigatiebalk. In die gevallen (of een soortgelijk geval), kunt u het aantal pixels van uw scroll verminderen om de optimale locatie te bereiken. Bijvoorbeeld: $('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow');brengt je naar de targetmet 15 pixels over aan de bovenkant.


Antwoord 8

Ik bleef bij mijn originele code en voegde ook een fade-in ‘back-to-top’-link toe door gebruik te maken van deze code en ook een beetje van hier:

http://webdesignerwall.com/tutorials/animated-scroll-to-top

Werkt goed 🙂


Antwoord 9

Misschien wilt u de waarde offsetTopen scrollToptoevoegen voor het geval u niet de hele pagina animeert, maar eerder geneste inhoud.

bijv. :

var itemTop= $('.letter[name="'+id+'"]').offset().top;
var offsetTop = $someWrapper.offset().top;
var scrollTop = $someWrapper.scrollTop();
var y = scrollTop + letterTop - offsetTop
this.manage_list_wrap.animate({
  scrollTop: y
}, 1000);

Antwoord 10

SS langzaam scrollen

Voor deze oplossing zijn geen ankertags vereist, maar u moet natuurlijk wel de menuknop (willekeurig kenmerk, ‘ss’ in het voorbeeld) matchen met het bestemmingselement-ID in uw html.

ss="about"brengt je naar id="about"

$('.menu-item').click(function() {
	var keyword = $(this).attr('ss');
	var scrollTo = $('#' + keyword);
	$('html, body').animate({
		scrollTop: scrollTo.offset().top
	}, 'slow');
});
.menu-wrapper {
  display: flex;
  margin-bottom: 500px;
}
.menu-item {
  display: flex;
  justify-content: center;
  flex: 1;
  font-size: 20px;
  line-height: 30px;
  color: hsla(0, 0%, 80%, 1);
  background-color: hsla(0, 0%, 20%, 1);
  cursor: pointer;
}
.menu-item:hover {
  background-color: hsla(0, 40%, 40%, 1);
}
.content-block-header {
  display: flex;
  justify-content: center;
  font-size: 20px;
  line-height: 30px;
  color: hsla(0, 0%, 90%, 1);
  background-color: hsla(0, 50%, 50%, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="menu-wrapper">
  <div class="menu-item" ss="about">About Us</div>
  <div class="menu-item" ss="services">Services</div>
  <div class="menu-item" ss="contact">Contact</div>
</div>
<div class="content-block-header" id="about">About Us</div>
<div class="content-block">
  Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.
That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>
<div class="content-block-header" id="services">Services</div>
<div class="content-block">
Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.
That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>
<div class="content-block-header" id="contact">Contact</div>
<div class="content-block">
  Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.
That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>

Antwoord 11

Ik kwam dit voorbeeld tegen op https://css-tricks.com/ snippets/jquery/smooth-scrolling/met uitleg over elke regel code. Dit vond ik de beste optie.

https://css-tricks.com/snippets/jquery/smooth- scrollen/

Je kunt native gaan:

window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth' 
});
window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

of met jQuery:

$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {
    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) {
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
      }
    }
  });

Antwoord 12

Ok, eenvoudigste methode is: –

Binnen de klikfunctie (Jquery): –

$('html,body').animate({scrollTop: $("#resultsdiv").offset().top},'slow');

HTML

<div id="resultsdiv">Where I want to scroll to</div>

Antwoord 13

$(function() {
    $('a#top').click(function() {
        $('html,body').animate({'scrollTop' : 0},1000);
    });
});

Test het hier:

http://jsbin.com/ucati4


Antwoord 14

de volgende oplossing werkte voor mij:

$("a[href^=#]").click(function(e)
        {
            e.preventDefault();
            var aid = $(this).attr('href');
            console.log(aid);
            aid = aid.replace("#", "");
            var aTag = $("a[name='"+ aid +"']");
            if(aTag == null || aTag.offset() == null)
                aTag = $("a[id='"+ aid +"']");
            $('html,body').animate({scrollTop: aTag.offset().top}, 1000);
        }
    );

Other episodes