我有一个带点导航和锚点链接的页面。 但我希望锚点链接转到该部分的中间,即使窗口大小,也会在页面的中心垂直居中,如下所示:
大窗口:
小窗口:
此外,如何使用突出显示的链接进行点导航?像这样的点导航:https://www.gumtreejobs.sg/当您在该部分时,该点为绿色。
HTML:
<div class="nav">
<a href="#section01">01</a>
<a href="#section02">02</a>
<a href="#section03">03</a>
<a href="#section04">04</a>
</div>
<div class="content">
<div class="section" id="section01">Section 01</div>
<div class="section" id="section02">Section 02</div>
<div class="section" id="section03">Section 03</div>
<div class="section" id="section04">Section 04</div>
</div>
CSS:
body {
margin:0;
}
.nav {
position:fixed;
right:0;
}
.nav a {
display:block;
margin:10px;
height:30px;
width:30px;
border-radius:100%;
background:grey;
}
.nav a:hover {
background: orange;
}
.nav a.active{
background: red;
}
.section {
height:200px;
background:pink;
margin:100px;
}
答案 0 :(得分:1)
以下是您想要的jsFiddle:https://jsfiddle.net/5oz0uzuz/1/
示例代码:
$('a').click(function(){
var $elem = $($(this).attr("href"));
var offset = $elem.offset().top - ($(window).height() / 2) + ($elem.height() / 2);
$('html, body').animate({
scrollTop: offset
}, 400);
$(this).addClass("active").siblings().removeClass("active");
return false;
});
首先,我在点击处理程序中添加了活动类,并将其从所有兄弟中删除。这样就可以确保当前项目始终具有该类。
对于滚动部分,您只需要将目标元素的一半高度添加到滚动中。
我希望这会有所帮助
答案 1 :(得分:0)
在动画之前添加此内部单击功能以添加锚点的活动类。
$('.nav a').removeClass('active');
$(this).addClass('active');