Как вы можете использовать плавную прокрутку страницы с анимацией jQuery и обновлять URL одновременно? - PullRequest
0 голосов
/ 27 апреля 2020



Я использую функцию анимации jQuery с настраиваемой анимацией для запуска плавной прокрутки страниц на моем веб-сайте. Я использую функцию event.preventDefault () в конце моего кода, и с этой опцией страница прокручивается как следует, но не обновляет URL. Когда я удаляю этот вызов функции, он обновляет URL, но предварительно страница мерцает, а затем прокручивается. Я пробовал и без пользовательской анимации, но она все еще ведет себя так же. Есть ли решение для этого?

$(function () {
    $.extend($.easing,
        {
            easeInOutExpo: function (x, t, b, c, d) {
                t /= d / 2;
                if (t < 1) {
                    return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
                }
                t--;
                return c / 2 * (-Math.pow(2, -10 * t) + 2) + b;
            }
        }
    );

    $('a.page-scroll').on('click', function (event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1600, 'easeInOutExpo');
        event.preventDefault();
    });
});

1 Ответ

0 голосов
/ 07 мая 2020

Я взломал ваш html / javascript на одной странице. Короче говоря - используйте плагин https://github.com/mathiasbynens/jquery-smooth-scrolling/blob/master/jquery.smoothscroll.js (вот откуда javascript)

Хотя люди говорят, что используют «плавную прокрутку» https://www.w3schools.com/cssref/pr_scroll-behavior.asp Но я не смог заставить это работать

Тем не менее, похоже, что это конечная строка

$scrollElement.stop().animate({ 'scrollTop': $hash.offset().top }, speed, function() {
                        location.hash = hash;
                    });

Так что, как правило, после завершения анимации обновите ссылку.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Smooth scroll</title>
    <style>
        #sneaker {
  margin-top: 1500px; 
  width: 100%;
}
    </style>
</head>
<body>
    <div id="main-container">
      <a class="page-scroll" href="#sneaker">Take you to the sneaker</a>
      <img id="sneaker" src="adidas-superstar-2-white-black.jpg" alt="adidas superstar sneaker">
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
    <script >
    /*! http://mths.be/smoothscroll v1.5.2 by @mathias */
;(function(document, $) {

    var $scrollElement = (function() {
        // Find out what to scroll (html or body)
            var $html = $(document.documentElement),
                $body = $(document.body),
                bodyScrollTop;
            if ($html.scrollTop()) {
                return $html;
            } else {
                bodyScrollTop = $body.scrollTop();
                // If scrolling the body doesn’t do anything
                if ($body.scrollTop(bodyScrollTop + 1).scrollTop() == bodyScrollTop) {
                    return $html;
                } else {
                    // We actually scrolled, so undo it
                    return $body.scrollTop(bodyScrollTop);
                }
            }
        }());

    $.fn.smoothScroll = function(speed) {
        speed = ~~speed || 400;
        // Look for links to anchors (on any page)
        return this.find('a[href*="#"]').click(function(event) {
            var hash = this.hash,
                $hash = $(hash); // The in-document element the link points to
            // If it’s a link to an anchor in the same document
            if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') && location.hostname === this.hostname) {
                // If the anchor actually exists…
                if ($hash.length) {
                    // …don’t jump to the link right away…
                    event.preventDefault();
                    // …and smoothly scroll to it
                    $scrollElement.stop().animate({ 'scrollTop': $hash.offset().top }, speed, function() {
                        location.hash = hash;
                    });
                }
            }
        }).end();
    };

}(document, jQuery));
    </script>
    <script>

        $('html').smoothScroll();

    </script>
</body>
</html>
...