簡體   English   中英

頁面加載后,如果不在視圖中,則在容器內自動滾動到活動水平元素

[英]Auto-scroll to active horizontal element when not in view, within a container, after the page loads

我為水平滾動導航元素創建了一個JSfiddle: https ://jsfiddle.net/sstracy/goe8j3sv/

從外觀上看,它會按我希望的方式加載到頁面上,但當建立活動導航項距左側太遠時,較小的屏幕將隱藏活動鏈接。 頁面加載后,我希望水平導航滾動到右側,直到顯示活動項。 否則,該功能將按我想要的方式工作。

在此測試階段,導航中的所有鏈接都不會到達任何地方,但是在最終版本中,它們會將用戶定向到不同的頁面,所有頁面都具有相同的基本導航代碼。 唯一的區別是,每個頁面將具有一個特定的正文標記類,該類與每個導航鏈接中提供的ID匹配。

我知道代碼不是最干凈的,因為我在這里開始使用JS和jQuery的混合方式...因此,使用兩者之一的解決方案都很好。

我已經啟動了一些代碼,希望可以使導航滾動,但是它不起作用:

JS行146-158:

// Scroll if selected item is not in view when the page loads but not after or during user interaction.
            var ids, matches = document.body.className.match(/(^|\s)hpn-(\d+)(\s|$)/);
            if (matches) {
                // found the id
                ids = matches[0];

                var $elem = ids;

                var navPosition = $('#pnProductNav').scrollLeft(),
                    elemPosition = document.getElementById(ids).offset().left;

                $("#pnProductNav").animate({scrollLeft: navPosition + elemPosition}, 800);
            }
  • 首先,我從body div中找到一個以“ hpn-”開頭的類。
  • 如果存在匹配的正文類,則將其放在變量“ ids”中,然后放入“ $ elem”中。
  • 然后,我試圖找到link元素距左側的距離,以便可以向右滾動動畫。 我認為這是我的不足之處,因為導航欄不會在頁面加載時滾動,而鏈接“機架”或“ hpn-19”是活動鏈接。

任何幫助將不勝感激,在提供幫助之前,我很樂意回答任何問題以清除所有問題!

我想我真的只是在想這個。 我終於明白了:

    // Scroll if selected item is not in view when the page loads but not after or during. 
    // First, find and get body class name that starts with hpn-
    var ids, matches = document.body.className.match(/(^|\s)hpn-(\d+)(\s|$)/);
    if (matches) {

        // found the id so define it
        ids = matches[0];

        // Get position of the nav bar and the position of the link with the matching ID
        var navPosition = $('#pnProductNav').scrollLeft(),
            elemPosition = $('#' + ids).offset().left;

        // Add the two together to get your scroll distance and animate    
        $("#pnProductNav").animate({scrollLeft: navPosition + elemPosition}, 800);
    }

https://jsfiddle.net/sstracy/goe8j3sv/12/

暫無
暫無

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

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