![](/img/trans.png)
[英]How to auto-scroll to a selected horizontal element not in view, within a container, when the page loads
[英]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);
}
任何幫助將不勝感激,在提供幫助之前,我很樂意回答任何問題以清除所有問題!
我想我真的只是在想這個。 我終於明白了:
// 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.