Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   снова скрол с алиасом (https://javascript.ru/forum/dom-window/81500-snova-skrol-s-aliasom.html)

venom1996 07.12.2020 11:16

снова скрол с алиасом
 
var lastId,
    topMenu = $("#article-nav"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
        var item = $($(this).attr("href"));
        if (item.length) { return item; }
    });

// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
    var href = $(this).attr("href"),
        offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
    $('html, body').stop().animate({
        scrollTop: offsetTop
    }, 300);
    e.preventDefault();
});

// Bind to scroll
$(window).scroll(function(){
    // Get container scroll position
    var fromTop = $(this).scrollTop()+topMenuHeight;

    // Get id of current scroll item
    var cur = scrollItems.map(function(){
        if ($(this).offset().top < fromTop)
            return this;
    });
    // Get the id of the current element
    cur = cur[cur.length-1];
    var id = cur && cur.length ? cur[0].id : "";

    if (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("isActive")
         .end().filter("[href='#"+id+"']").parent().addClass("isActive");
   } 
});

ошибку показывает в этой строке
offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
<a href="тут-какой-то-алиас#ссылка на элемент">
с алиасом перестал работать скрол,
<a href="#ссылка-на-элемент">
вот так работало без проблем

voraa 07.12.2020 12:22

А что по вашему выдаст jQuery на
$("тут-какой-то-алиас#ссылка на элемент")

venom1996 07.12.2020 12:25

ну а как явно указать что впереди идёт строка, а потом якорь ?

voraa 07.12.2020 12:27

Ищите в строке '#' и выбираете из строки все, что идет, начиная с '#' до конца.

venom1996 08.12.2020 16:23

Цитата:

Сообщение от voraa (Сообщение 531490)
Ищите в строке '#' и выбираете из строки все, что идет, начиная с '#' до конца.

можно пример ?

venom1996 08.12.2020 17:37

var href = $(this).attr("href")
  var world = href.substring('39', 100),
     offsetTop = world === "#" ? 0 : $(world).offset().top-topMenuHeight + 5;


я попробовал так, но у меня алиасы имеют разные количество символов, какой функцией можно найти "#" и всё что до него удалить ?

voraa 08.12.2020 18:18

Строка вида
'<alias>#<elem>'

Способ 1

let href = $(this).attr("href");
let n = href.indexOf('#');
let alias = href.slice(0,n);
let elem = href.slice(n+1);

https://developer.mozilla.org/ru/doc...String/indexOf
https://developer.mozilla.org/ru/doc...s/String/slice

Способ 2

let [alias, elem] = $(this).attr("href").split('#');

https://developer.mozilla.org/ru/doc...s/String/split
https://learn.javascript.ru/destructuring-assignment

venom1996 09.12.2020 12:23

Цитата:

Сообщение от voraa (Сообщение 531557)
Строка вида
'<alias>#<elem>'

Способ 1

let href = $(this).attr("href");
let n = href.indexOf('#');
let alias = href.slice(0,n);
let elem = href.slice(n+1);

https://developer.mozilla.org/ru/doc...String/indexOf
https://developer.mozilla.org/ru/doc...s/String/slice

Способ 2

let [alias, elem] = $(this).attr("href").split('#');

https://developer.mozilla.org/ru/doc...s/String/split
https://learn.javascript.ru/destructuring-assignment


спасибо за ответ) но я поступил иначе
var href = $(this).attr("href")
  var shref = href.replace(/.+(?=#)/, ''),
     offsetTop = shref === "#" ? 0 : $(shref).offset().top-topMenuHeight + 1;


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