关于vh的滚动条事件

我自己想做一个 demo,使用了 vh 来定义了 4 个 section,然后想在滚动的时候显示对应的 a 锚点链接的背景颜色。请问实现的思路是怎么样的呢?以及有关的 js 代码。。

我在鼠标点击中使用了锚点来进行跳转,但是关于滚动条滚动时的 scrollTop 不能使用 vh,所以我很想搞明白使用什么方式来实现,其中我也想用到 classList 来 toggle 其中对应的 class,但是代码我却想不出来。

谢谢各位。

HTML:

<section id="bar-1" style="width: 100vw; height: 100vh; background: pink"></section>
<section id="bar-2" style="width: 100vw; height: 100vh; background: red"></section>
<section id="bar-3" style="width: 100vw; height: 100vh; background: dodgerblue"></section>
<section id="bar-4" style="width: 100vw; height: 100vh; background: purple"></section>

<div id="bar">
  <ul>
    <li><a href="#bar-1" class="active"></a></li>
    <li><a href="#bar-2"></a></li>
    <li><a href="#bar-3"></a></li>
    <li><a href="#bar-4"></a></li>
  </ul>
</div>

效果图:
效果图

阅读 2.4k
1 个回答

这样不就可以了吗?$("#bar-1").position().top

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
    <style>
        *{padding:0;margin:0}
        #bar{position:fixed;top:0;bottom:0;right:0;height:4em;width:1em;
            margin:auto;
            }
        ul{list-style:none;}
    </style>
</head>
<body>
<section id="bar-1" style="width: 100vw; height: 100vh; background: pink"></section>
<section id="bar-2" style="width: 100vw; height: 100vh; background: red"></section>
<section id="bar-3" style="width: 100vw; height: 100vh; background: dodgerblue"></section>
<section id="bar-4" style="width: 100vw; height: 100vh; background: purple"></section>

<div id="bar">
  <ul>
    <li><a href="#bar-1" class="active">·</a></li>
    <li><a href="#bar-2"></a>·</li>
    <li><a href="#bar-3"></a>·</li>
    <li><a href="#bar-4"></a>·</li>
  </ul>
</div>
<script>
    console.log($("#bar-1").position().top);
    console.log($("#bar-2").position().top);
    console.log($("#bar-3").position().top);
    console.log($("#bar-4").position().top);
</script>
    
</body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题