我正在尝试构建一个单独的页面,其上面有一个固定的菜单,其中活动选项卡将根据水平滚动位置而改变。作为一个初学者,我想找出我的代码中的错误,而不是使用jQuery插件。任何帮助纠正我的JavaScript代码都将非常感激。
HTML
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Test scrollLeft</title>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1 /jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<nav>
<ul id="menu">
<li><a id="one" class="active" href="#foo">Accueil</a></li>
<li><a id="two" href="#bar">Infos</a></li>
<li><a id="three" href="#baz">Contact</a></li>
</ul>
</nav>
<section class="page" id="foo">
<h2>Accueil</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</section>
<section class="page" id="bar">
<h2>Infos</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</section>
<section class="page" id="baz">
<h2>Contact</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</section>
<div class="result"><span id="result"></span></div>
</body>
</html>
CSS
html, body {
height: 100%;
overflow-y: hidden;
margin:0px; padding: 0 0 0 0;
}
body {
width:4500px;
font-family: Helvetica, Arial;
}
.page {
height:100%;
float: left;
width: 1500px;
}
.page h2 {
padding: 50px 0 0 20px;
}
.page p {
width: 500px;
padding: 0 0 0 20px;
}
div.page p {
height: 900px;
margin-top: 50px;
}
div.result {
margin: 10px;
width: 100px;
height: 100px;
margin: 5px;
float: left;
color: white;
background-color: blue;
position: fixed;
right: 0;
bottom: 0;
}
#foo {
background-color: #e4e4e4;
}
#bar {
background-color: #c4c4c4;
}
#baz {
background-color: #a9a9a9;
}
#menu {
position: fixed;
z-index: 1;
background: #d68aa5;
left: 0;
right: 0;
top: 0;
}
#menu li {
float: left;
display: block;
}
#menu a {
display: block;
padding: 5px 25px 7px 25px;
transition: 1s all ease;
color: #fff;
text-decoration: none;
}
#menu a:hover {
color: #000;
}
.active {background-color: #000; color: #fff!important;}
JAVASCRIPT
$(document).ready(function(){
$(window).mousemove(function () {
var currentScrollLeft = $(window).scrollLeft();
$("#result").html(currentScrollLeft);
switch(currentScrollLeft) {
case (($currentScrollLeft >= 0) && ($currentScrollLeft <= 1499)):
$('#one').addClass('active');
break;
case (($currentScrollLeft >= 1500) && ($currentScrollLeft <= 2999)):
$('#two').addClass('active');
break;
case (($currentScrollLeft >= 3000) && ($currentScrollLeft <= 4500)):
$('#three').addClass('active');
break;
}
});
});
答案 0 :(得分:2)
看看这个fiddle链接,这里我已经更新了您的来源以解决问题。我希望这对你有帮助。
而不是switch语句
switch(cond){}
你可以使用if语句
if(cond){}
如果语句可以减少更多问题,因为switch无法使用动态变量值运行,这意味着您只能在switch中使用常量值。