我在div <div id="Section1"> abc </div>
中有一个ID并且链接<a id="link" href="#Section1">Section1</a>
问题:当我在ID #Section1
滚动页面和页面覆盖时,应该在链接中添加一个类,链接应该像<a id="link" href="#Section1" class="ok">Section1</a>
答案 0 :(得分:5)
您可以这样使用:
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
$('#link').toggleClass('ok',
//add 'ok' class when div position match or exceeds else remove the 'ok' class.
scroll >= $('#Section1').offset().top
);
});
//trigger the scroll
$(window).scroll();//ensure if you're in current position when page is refreshed
请参阅toggleClass的文档。
答案 1 :(得分:0)
如果有人在寻找一个好的库,我通常会使用 waypoints.js + inview 来进行此类滚动事件。它提供了一个很好的API来了解元素何时进入和离开等等。
示例代码:
var inview = new Waypoint.Inview({
element: $('#inview-example')[0],
enter: function(direction) {
notify('Enter triggered with direction ' + direction)
},
entered: function(direction) {
notify('Entered triggered with direction ' + direction)
},
exit: function(direction) {
notify('Exit triggered with direction ' + direction)
},
exited: function(direction) {
notify('Exited triggered with direction ' + direction)
}
});
需要:
<script src="/path/to/lib/jquery.waypoints.min.js"></script>
<script src="/path/to/shortcuts/inview.min.js"></script>