質問

i added this script for internal links scroll gestion on my website:

$(document).ready(function() {
    // Pour tous les liens commençant par #.
    $("a[href^='#']").click(function (e) {
        // On annule le comportement initial au cas ou la base soit différente de la page courante.
        e.preventDefault();


        // On ajoute le hash dans l'url.
        window.location.hash = $(this).attr("href");

        $('body').animate({
            scrollTop: $(window.location.hash).offset().top - 72
        }, 'slow');

        return false
    });
});

The script does not work perfectly. At the first clic, We're going in the right place, but the scroll does not work. However, from the second click, scroll work properly.

Edit:

My html code:

<a class="link-icon visible-desktop" href="#home-keyNumbers-section"><img src="{{ asset('/bundles/visualimmersionsite/images/icons/Arrowhead-Down-256-hover.png') }}" alt="Scroller pour mieux nous connaître" /> </a>

<section id="home-keyNumbers-section" name="home-keyNumbers-section" class="designed-section-2 ">
        <div class="container">
            {%  include 'VisualImmersionSiteBundle:Site:templates/key_numbers_template.html.twig' %}
        </div>


    </section>

Have you an idea ?

Thanks for your help :)

役に立ちましたか?

解決

window.location.hash = $(this).attr("href");

This is still going to cause the viewport to scroll; it’s more or less equivalent to just clicking the link. You can use the History API to push a new URL without causing it to be “visited”:

history.pushState(null, null, $(this).attr('href'));

If you need to support IE8 and earlier, it might work to hold onto the current scroll position:

var originalScroll = window.scrollY; // Grab window.scrollX if applicable
window.location.hash = $(this).attr("href");
window.scrollY = originalScroll;

You might have to put the window.scrollY = originalScroll in a setTimeout with a timeout of 0, though.

他のヒント

Your code should be:

$(document).ready(function () {
    // Pour tous les liens commençant par #.
    $("a[href^='#']").click(function (e) {

        $('body, html').animate({
            scrollTop: $($(this).attr("href")).offset().top - 72
        }, 'slow', function () {
            // On ajoute le hash dans l'url.
            window.location.hash = $(this).attr("href");
        });

        return false
    });
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top