我已为我的导航编写了此代码。它会对元素进行计数,并通过向下滚动来检查是否到达了该区域。然后,它将活动类设置为导航中的右侧条目,并从li中删除旧的活动。
所以这适用于桌面,但不适用于移动设备。我给第一个元素(Home)激活。滚动到下一部分后,活动状态不会删除第一个li,并且它没有添加到新的li中。
所以这是我的HTML代码:
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#" onclick='location.reload(true); return false;' target="_self"><img width="155px" height="auto" alt="Media Solutions GmbH" src="../misc/images/ms_logo.gif"></a>
</div>
<div id="navbar" class="navbar-collapse collapse pull-right">
<ul class="nav navbar-nav">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#about">Digitalisierung</a></li>
<li><a href="#usecase">Einsatzbereiche</a></li>
<li><a href="#benefit">Ihr Nutzen</a></li>
<li><a href="#service">Unsere Leistungen</a></li>
<li><a href="#contact">Kontakt</a></li>
<li class="dropdown">
<a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#">Weitere Informationen <span class="caret"></span></a>
<?php include '../includes/naviInner.php'; ?>
</li>
</ul>
</div><!--/.navbar-collapse -->
</div>
在这里我的Jquery:
//navigation
var navHeight = $('nav').height();
var scroll_pos = 0;
//NavBar
var aNavBar = $.map($(".marker"), function(n, i){
return n.id;
});
//var aNavBar = ['home','about','prozess','vorteile','team','kontakt'];
var oNavBar = { 0: [0,0,1] };
// MenuName || Offset+NavHeight || Index || ChildIndex
for (i=1; i<aNavBar.length; i++) {
var myOffset =$("#"+aNavBar[i]).offset().top;
oNavBar[i] = [ myOffset, i, i+1 ];
}
$(document).scroll(function() {
var curr_scroll_pos = $(this).scrollTop() + 30;
var bMatchFound = false;
for (i=0; i<aNavBar.length-1; i++) {
if ( oNavBar[i][0] <= curr_scroll_pos && curr_scroll_pos < oNavBar[i+1][0]) {
myChildIndex = oNavBar[i][2];
//Construct selector string
mySelector = "nav .nav > li:nth-child(" + myChildIndex + ")";
//Assign classes
$("nav .nav > li").removeClass("active");
$(mySelector).addClass("active");
bMatchFound = true;
break;
}
}
//We reached the last NavBar-Element
if (!bMatchFound) {
mySelector = "nav .nav > li:nth-child(" + oNavBar[aNavBar.length-1][2] + ")";
$("nav .nav > li").removeClass("active");
$(mySelector).addClass("active");
}
});
它在桌面上运行良好,但它不会在移动设备的导航中标记活动区域:(请帮助!仅限移动设备&#34; Home&#34;将设置为活动状态,因为它在html中硬编码看起来JS对导航没有任何影响。
谢谢!