javascript - 单页点导航

标签 javascript jquery html css navigation

我有一个带有点导航和 anchor 链接的页面。 但我希望 anchor 链接转到该部分的中间,在页面中垂直居中,即使窗口大小也是如此,如下所示:

大窗口:

enter image description here

较小的窗口:

enter image description here 此外,如何使用突出显示的链接进行点导航?喜欢这个点导航:https://www.gumtreejobs.sg/当您在该部分时,点为绿色。

MY JSFIDDLE

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;

  }

最佳答案

这是一个包含你想要的东西的 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;
 });

首先,我在点击处理程序上添加了 active 类,并将其从所有同级中删除。这样您就可以确保当前元素始终具有该类。

对于滚动部分,您只需将目标元素的高度的一半添加到滚动即可。

希望对你有帮助

关于javascript - 单页点导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41380371/

相关文章:

javascript - preg_match_all 获取除 tabmanager 脚本之外的所有脚本选项卡

javascript - 换行时html文本元素的宽度

javascript - jQuery .load() 无法在 jQuery load() 加载的另一个内容中工作

javascript - 输入长度大于 0 不能正常工作

php - 如何使用 JavaScript 和 PHP 来存储变量?

jQuery addClass 到每个具有 '.class' 子级的元素

html - 内联 block CSS

javascript - jQuery Draggable 拖出屏幕

javascript - jQuery 不适用于文档加载后创建的元素

javascript - 从主脚本文件中分离数组