admin管理员组

文章数量:1419251

I have the following script that provides an anchor effect:

// Smooth scrolling when clicking on a hash link
    $('a[href*="#"]').on('click', function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        if ($(window).width() > 1023) {
            var $scrollTop = $target.offset().top - 120;
        } else {
            var $scrollTop = $target.offset().top;
        }

        $('html, body').stop().animate({
            'scrollTop': $scrollTop
        }, 900, 'swing');
    });

The problem is that this only works on home page, but in the other pages it does not work because I need to provide the web link (www.url/#anchor). But if I do this, the effect does not apply. someone knows how to add to the effect, for example get_site_url ('/#anchor/'); , and so this always take the url of the web as a base?

I hope I have expressed myself well. Greetings and thanks

I have the following script that provides an anchor effect:

// Smooth scrolling when clicking on a hash link
    $('a[href*="#"]').on('click', function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        if ($(window).width() > 1023) {
            var $scrollTop = $target.offset().top - 120;
        } else {
            var $scrollTop = $target.offset().top;
        }

        $('html, body').stop().animate({
            'scrollTop': $scrollTop
        }, 900, 'swing');
    });

The problem is that this only works on home page, but in the other pages it does not work because I need to provide the web link (www.url/#anchor). But if I do this, the effect does not apply. someone knows how to add to the effect, for example get_site_url ('/#anchor/'); , and so this always take the url of the web as a base?

I hope I have expressed myself well. Greetings and thanks

Share Improve this question asked Jul 24, 2019 at 10:52 Dario B.Dario B. 15510 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

CSS now has the property scroll-behavior (browser support is there but not so great). You can use it as described here:

html {
  scroll-behavior: smooth;
}

@media (prefers-reduced-motion: reduce) {
  html {
    scroll-behavior: auto;
  }
}

If this doesn't work for you, you're stuck with JS. The problem is, on a new page load, browsers automatically jump to the position of the fragment. But there is a workaround as described in this StackOverflow answer:

// to top right away
if (window.location.hash) scroll(0,0);
// void some browsers issue
setTimeout(function() { scroll(0,0); }, 1);

$(function() {
    // *only* if we have anchor on the url
    if(window.location.hash) {
        // smooth scroll to the anchor id
        $('html, body').animate({
            scrollTop: $(window.location.hash).offset().top + 'px'
        }, 1000, 'swing');
    }

});

本文标签: menusjquery anchor effect does not work properly