在这里,我创建了四个 div 的红色、蓝色、绿色和黄色以及一个链接到各个 div 的导航菜单。当我单击导航上的链接时,我希望相应的 div 动画并滚动到顶部。
我是 jQuery 新手,所以我很难找出解决方案。您能提供的任何帮助将不胜感激。
下面是 HTML、CSS 和 jquery。
HTML
<body>
<div id="wrapper">
<div id="mainContent">
<div id="redPage" class="red">
<p>Red</p>
</div>
<div id="bluePage" class="blue">
<p>blue</p>
</div>
<div id="greenPage" class="green">
<p>green</p>
</div>
<div id="yellowPage" class="yellow">
<p>yellow</p>
</div>
</div>
<nav>
<ul>
<a href="#redPage">
<li class="red">Red</li>
</a>
<a href="#bluePage">
<li class="blue">Blue</li>
</a>
<a href="#greenPage">
<li class="green">Green</li>
</a>
<a href="#yellowPage">
<li class="yellow">Yellow</li>
</a>
</ul>
</nav>
</div>
</body>
CSS
* {
padding: 0px;
margin: 0px;
text-decoration: none;
}
body {
overflow: hidden;
}
#wrapper {
width: 960px;
height: 500px;
margin: 20px auto;
}
#mainContent {
float: right;
width: 800px;
height: 500px;
overflow: hidden;
}
#redPage {
width: 800px;
height: 500px;
overflow-y: scroll;
}
#bluePage {
width: 800px;
height: 500px;
overflow-y: scroll;
}
#greenPage {
width: 800px;
height: 500px;
overflow-y: scroll;
}
#yellowPage {
width: 800px;
height: 500px;
overflow-y: scroll;
}
nav {
float: left;
width: 160px;
}
nav li {
list-style-type: none;
display: block;
width: 100px;
height: 50px;
margin: 30px 0px 0px 0px;
text-decoration: none;
text-align: center;
box-sizing: border-box;
padding-top: 10px;
padding-left: 10px;
font-size: 24px;
line-height: 30px;
color: white;
}
.red {
background: red;
}
.blue {
background: blue;
}
.green {
background: green;
}
.yellow {
background: yellow;
}
jQuery
<script>
$('document').ready(function() {
$('a[href^="#"]').click(function(){
var $target=$(this.hash);
if($target.length==0) $target=$('a[name=" '+this.hash.substr(1)+' "]');
if($target.length==0) $target=$('#mainContent');
$("#mainContent").animate({scrollTop:$target.position().top},900);
return false;
});
});
</script>