[英]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.