>  Q&A  >  본문

javascript - 关于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>

<p 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>
</p>

效果图:

迷茫迷茫2724일 전442

모든 응답(1)나는 대답할 것이다

  • PHPz

    PHPz2017-04-11 11:42:51

    这样不就可以了吗?$("#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>
    
    <p 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>
    </p>
    <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>

    회신하다
    0
  • 취소회신하다