代码之家  ›  专栏  ›  技术社区  ›  HELP

如何使用javascript在div not窗口上滚动?

  •  -1
  • HELP  · 技术社区  · 6 年前

    在这里,当我滚动窗口时,我的进度条和那个进度条会移动。

    但我想当我滚动窗口时,它检测div而不是窗口。 我为window编写代码,它在window scroll上完美地完成了我的工作。

    这是我的密码

    $(window).scroll(function () {
            var scroll = $(window).scrollTop(),
                documentHeight = $(document).height(),
                windowHeight = $(window).height();
                scrollPercent = (scroll / (documentHeight-windowHeight)) * 100;
                var position = scrollPercent;
    
        $("#progressbar").attr('value', position);
    
        });
    progress {
            height: 6px;
            width: 100%;
            position:fixed;
            margin-left: -48px;
            margin-top: -20px;
        }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div type="slideshow" id ="slide">
    <section>
      <header>date </header>
      <section>content</section>
    </section>
    <section>
      <header>date </header>
      <section>content</section>
    </section>
    <section>
      <header>date </header>
      <section>content</section>
    </section>
    <section>
      <header>date </header>
      <section>content</section>
    </section>
    </div>

    我应该如何在我的div上编写此代码。 我们将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  1
  •   wayneOS    6 年前

    我稍微修改了您的代码,为您提供了一个我认为您想要的解决方案。与您检查的方式相同 window 对于 scrollTop height 可用于 div 。请注意,为了使此示例正常工作,我将div的高度限制为 100px

    $('#slide').scroll(function () {
      var scroll        = $(this).scrollTop();
      var scroll_height = $(this).get(0).scrollHeight;
      var height        = $(this).height ();
      var percent       = scroll / (scroll_height - height) * 100;
    
      $("#progressbar").text (percent);
    });
    #progressbar {
      border:     1px solid #000;
    }
    
    #slide {
      height:     100px;
      border:     1px solid #000;
      overflow-y: scroll;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="progressbar">0</div>
    
    <br><br>
    
    <div type="slideshow" id="slide">
      <section>
        <header>date </header>
        <section>content</section>
      </section>
      <section>
        <header>date </header>
        <section>content</section>
      </section>
      <section>
        <header>date </header>
        <section>content</section>
      </section>
      <section>
        <header>date </header>
        <section>content</section>
      </section>
      <section>
        <header>date </header>
        <section>content</section>
      </section>
      <section>
        <header>date </header>
        <section>content</section>
      </section>
      <section>
        <header>date </header>
        <section>content</section>
      </section>
      <section>
        <header>date </header>
        <section>content</section>
      </section>
    </div>