Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   скрол не по id (https://javascript.ru/forum/dom-window/81394-skrol-ne-po-id.html)

venom1996 19.11.2020 16:20

скрол не по id
 
$(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");
                }
            });
        }
    }
});

есть такой код который скролит к нужному блоку по id, как его переделать что бы он скролил по #(якорь)

рони 19.11.2020 17:13

venom1996,
информации недостаточно, но возможно так ...
$(document).on("click", ".header-nav__dropdown li a", function(e) {
    var dropdownParent = $(this).closest(".header-nav__list>ul>li");
    if (dropdownParent.hasClass("isActive")) {
        var hash = this.hash;
        if (hash) {
            e.preventDefault();
            scrollToSection(hash.slice(1));
            $(this).closest(".header-nav__dropdown").hide({
                duration: 100,
                complete: function complete() {
                    $(this).removeAttr("style");
                }
            });
        }
    }
});

venom1996 19.11.2020 17:16

//Прокрутка до блока по id из get параметра в адресной строке
    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);
    }


вот полный код, уже голову сломал, переделываю ссылки под якори, но скрол пропал

рони 19.11.2020 17:26

Цитата:

Сообщение от рони
возможно так ...

это сработало?

venom1996 19.11.2020 17:30

нет к сожалению (

Nexus 19.11.2020 20:12

Попробуйте так:

$(() => {
    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.replace(/^#+/g, '')}"]`].join(', ')).first().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');
            }
        });
    });
});

рони 19.11.2020 20:28

Цитата:

Сообщение от Nexus
duration === undefined ? 800 : duration

?
почему условный оператор, а не строка 2 для назначения по умолчанию?

venom1996 19.11.2020 20:33

без понятия, это делал не я, мне было бы проще сделать с нуля чем работать с готовым

Nexus 19.11.2020 21:33

Цитата:

Сообщение от рони
почему условный оператор, а не строка 2 для назначения по умолчанию?

Хороший вопрос, на который у меня нет ответа :)

Спасибо, поправил.
p.s. код я не тестировал от слова «совсем».

venom1996 20.11.2020 00:12

не работает к сожалению, как только не пытался, дело в том что там cms modx и перед ссылками стоит это условие
<li class="[[!If? &subject=`[[*id]]` &operator=`eq` &operand=`1` &then=`isActive` ]]">


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