我在这里创建了四个 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>
最佳答案
关于jquery - 使用 jquery 动画并将 div 滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16969814/