簡體   English   中英

在頁面加載時,如果URL哈希與數組中的值之一匹配,請滾動到具有匹配的data-load-id屬性的元素

[英]On page load, if URL hash matches one of the values in the array, scroll to the element with the matching data-load-id attribute

我目前有以下內容:

var scrollingAnchorIds = [];
    var getTheseIds = $(".anchor-content").each(function() {
        scrollingAnchorIds.push($(this).data('load-id'));
    });
    console.log(scrollingAnchorIds);

    $(window).bind("load", function() {
        if(document.URL.indexOf(scrollingAnchorIds[i]) >= 0){ 
            $('html,body').animate({scrollTop: elementWithMatchingDataLoadIdGoesHere.offset().top - 50},850);
        }
    });

我得到每個data-load-id的值,並將它們添加到數組中。 現在,我要檢查頁面何時加載,URL是否包含該哈希值,如果是,請滾動到具有匹配值的元素。

滾動到哪個元素的示例html:

<div data-load-id="#83" class="anchor-content"></div>
<div data-load-id="#91" class="anchor-content"></div>
<div data-load-id="#99" class="anchor-content"></div>

考慮這一點時,您的大多數代碼似乎都過多了。 嘗試這樣的事情:

$(function(){
    $('html,body').animate({scrollTop: $("[data-load-id='" + window.location.hash + "']").offset().top - 50},850);
});

我也做了一個小提琴 ,盡管window.location.hash在此不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM