Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   плавная прокрутка (https://javascript.ru/forum/dom-window/81479-plavnaya-prokrutka.html)

venom1996 03.12.2020 17:49

плавная прокрутка
 
function GetURLParameter(sString, sParam) {
    if (sString.split("?")[1]) {
        var sURLVariables = sString.split("?")[1].split('&');
        for (var i = 0; i < sURLVariables.length; i++) {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam) {
                return sParameterName[1];
            }
        }
    }
}

 var URL = window.location.href;
if (GetURLParameter(URL, "id")) {
    setTimeout(function() {
        scrollToSection(GetURLParameter(URL, "id"), 0);
    }, 500);
}

//Прокрутка до блока при клике по выпадающему меню текущей страницы
$(document).on("click", ".header-nav__dropdown li a", function(e) {
    var dropdownParent = $(this).closest(".header-nav__list>ul>li");
    if (dropdownParent.hasClass("isActive")) {
        var linkHref = $(this).attr("href");
        if (GetURLParameter(linkHref, "id")) {
            e.preventDefault();
            scrollToSection(GetURLParameter(linkHref, "id"));
            $(this).closest(".header-nav__dropdown").hide({
                duration: 100,
                complete: function complete() {
                    $(this).removeAttr("style");
                }
            });
        }
    }
});

function scrollToSection(id) {
    var duration = arguments.length <= 1 || arguments[1] === undefined ? 800 : arguments[1];

    var delta = $(window).width() < 768 ? 0 : $(".header-nav").outerHeight();
    $("html,body").animate({
        scrollTop: $("#" + id).offset().top - delta
    }, duration);
}

не работает плавная прокрутка, после изменения ссылок, раньше было вот так
<li><a href="[[!getAliasRegion]]/[[~11]]?id=main_start">Наши достижения</a></li>
, сейчас изменил на
<li><a href="[[!getAliasRegion]]/[[~11]]#наши-достижения">Наши достижения</a></li>
, что мне поправить в функции что бы плавная прокрутка снова заработала ?

рони 03.12.2020 17:52

Цитата:

Сообщение от venom1996
что мне поправить в функции что бы плавная прокрутка снова заработала ?

https://javascript.ru/forum/dom-wind...tml#post530943

venom1996 03.12.2020 17:56

да не работает, там функция GetURLParameter не правильно берёт юрл

рони 03.12.2020 18:06

Цитата:

Сообщение от venom1996
там функция GetURLParameter не правильно берёт юрл

там нет функции GetURLParameter!!!

venom1996 04.12.2020 09:03

Цитата:

Сообщение от venom1996 (Сообщение 531384)
$(() => {
    const scrollTo = (target, duration = 800) => {
        if (!target) {
            return;
        }
        
        const delta = $(window).width() < 768 ? 0 : $('.header-nav').outerHeight();
        
        $('html,body').animate({
      scrollTop: $(`${target},a[name="${target.slice(1)}"]`).offset().top - delta //тут выстреливает ошибку
    }, duration);
    };

    if (location.hash) {
        scrollTo(location.hash);
    }
    
    $(document).on('click', '.header-nav__dropdown li a', function(e) {
        const $this = $(this);
        const hash = (this.href || '').split('#').pop();
        
        if ($this.closest('.header-nav__list > ul > li').hasClass('isActive') || !hash) {
            return;
        }
        
        e.preventDefault();
        
        scrollTo('#' + hash);
        
        $this.closest('.header-nav__dropdown').hide({
            duration: 100,
            complete: function () {
                this.removeAttribute('style');
            }
        });
    });
});

Syntax error, unrecognized expression: #%D0%B1%D0%B0%D0%BD%D0%BA%D1%80%D0%BE%D1%82%D1%81% D1%82%D0%B2%D0%BE_%D0%B8_%D0%B5%D0%B3%D0%BE_%D0%BF %D1%80%D0%B5%D0%B8%D0%BC%D1%83%D1%89%D0%B5%D1%81%D 1%82%D0%B2%D0%B0,a[name="%D0%B1%D0%B0%D0%BD%D0%BA%D1%80%D0%BE%D1%82%D 1%81%D1%82%D0%B2%D0%BE_%D0%B8_%D0%B5%D0%B3%D0%BE_% D0%BF%D1%80%D0%B5%D0%B8%D0%BC%D1%83%D1%89%D0%B5%D1 %81%D1%82%D0%B2%D0%B0"]

рони 04.12.2020 09:23

Цитата:

Сообщение от venom1996
<li><a href="[[!getAliasRegion]]/[[~11]]#наши-достижения">Наши достижения</a></li>

блок имеет id = "наши-достижения"?

venom1996 04.12.2020 09:24

конечно

venom1996 04.12.2020 09:29

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

      scrollTop: $(`${target},a[name="${target.slice(1)}"]`).offset().top - delta //тут выстреливает ошибку

    }, duration);

    };

 

    if (location.hash) {

        scrollTo(location.hash);

    }

в этих строчках показывает ошибку, сил уже никаких нет ) бьюсь с этим скролом недели 3

рони 04.12.2020 09:32

venom1996,
пост#8 строка 0
target = decodeURI(target);

рони 04.12.2020 09:51

venom1996,
смотрите, что у вас не так?
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  div{
      height: 500px;
  }

  </style>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  <script>
$(() => {
    const scrollTo = (target, duration = 800) => {
        if (!target) {
            return;
        }

        const delta = $(window).width() < 768 ? 0 : $('.header-nav').outerHeight();
        target = decodeURI(target);
        $('html,body').animate({
      scrollTop: $(`${target},a[name="${target.slice(1)}"]`).offset().top - delta
    }, duration);
    };

    if (location.hash) {
        scrollTo(location.hash);
    }

    $(document).on('click', '.header-nav__dropdown li a', function(e) {


        const $this = $(this);
        const hash = (this.href || '').split('#').pop();

        if ($this.closest('.header-nav__list > ul > li').hasClass('isActive') || !hash) {
            return;
        }
        e.preventDefault();

        scrollTo('#' + hash);

        $this.closest('.header-nav__dropdown').hide({
            duration: 100,
            complete: function () {
                this.removeAttribute('style');
            }
        });
    });
});

  </script>
</head>

<body>
<header class="header-nav">header-nav</header>
<ul class="header-nav__dropdown">
    <li><a href="#начало">Начало</a></li>
    <li><a href="#наши-достижения">Наши достижения Click me!</a></li>
</ul>
<div id="начало">начало</div>
<div id="наши-достижения">наши-достижения</div>
</body>
</html>


Часовой пояс GMT +3, время: 10:30.