【发布时间】:2013-09-11 16:52:02
【问题描述】:
我想试验一个我在一个很酷的网站上找到的功能,但我不知道从哪里开始。
该功能是随着页面向下滚动而移动的下划线元素。 我在这里找到了类似的 SO Underlining menu item 但如果有人可以帮助我在 id 之后使用该功能,我将不胜感激。对 Jquery 还不太熟悉。
提前致谢!
【问题讨论】:
-
我之前检查了您的个人资料,发现此问题未得到答复,请参阅下面的答案。干杯!
我想试验一个我在一个很酷的网站上找到的功能,但我不知道从哪里开始。
该功能是随着页面向下滚动而移动的下划线元素。 我在这里找到了类似的 SO Underlining menu item 但如果有人可以帮助我在 id 之后使用该功能,我将不胜感激。对 Jquery 还不太熟悉。
提前致谢!
【问题讨论】:
在您的示例网站上,每个<a> 标记都有一个<span> 元素用作下划线。但我在想也许我们可以切断标记并改用border-bottom。基本上这里有两个活动 - scroll() 和 click()。
这是基本的标记:
<nav>
<a>Home</a>
<a>About</a>
<a>Portfolio</a>
<a>Contact</a>
</nav>
<div id="contents">
<section>Home</section>
<section>About</section>
<section>Portfolio</section>
<section>Contact</section>
</div>
CSS,只是想强调边框:
a {
border:0 solid #FFF;
border-bottom-width:0;
}
jQuery scroll() 事件:
$(window).scroll(function () {
//get the window scrollTop on scroll
var st = $(window).scrollTop();
/* we use each() to iterate on every section and
check if the offset position is in relative condition to the
scrollTop value
*/
$('#contents section').each(function (index) {
var offsetTop = $(this).offset().top,
h = $(this).height();
//this condition satisfies that this section is currently on the viewport
if (st >= offsetTop && st < offsetTop + h) {
/*find the nav <a> that has the same index to this section
currently on the viewport and
show its border-bottom by setting its width.
*/
$('nav a').eq(index).css({
'border-bottom-width': '3px'
});
} else {
//hide the border-bottom
$('nav a').eq(index).css({
'border-bottom-width': '0'
});
}
});
}).trigger('scroll');
导航<a>click()事件:
$('nav a').click(function () {
/* click has no index argument compared to each() function
so we have to get it with index() */
var index = $(this).index(),
$target = $('#contents section').eq(index); // find the target section
//animate scrolling to the target section
$('html, body').stop(true, true).animate({
scrollTop: $target.offset().top
}, 'slow');
});
请注意,我们使用index 来定位确切的<section>/<a>,如果<section> 与导航<a> 排列位置相对应,则此解决方案将正常工作。
查看此示例jsfiddle。
【讨论】: