Javascript - 当window.pageYOffset已经为0时检测滚动尝试

时间:2016-10-27 16:21:11

标签: javascript jquery html css

我有一个div在页面加载下推出视图然后稍后暴露并推到top-bar并通过更改顶部样式来接管点击功能的其余部分我的功能是这样的:

$('#drawer').animate({
      top: 92
    }, 500);

我希望当div可见时,检测用户是否向上滚动,当它尝试向上滚动时,div向下滑动用户向上滚动的像素数量。我不确定如何做到这一点。

在我的脚本scroll-event.js中,我尝试设置一个函数,我将在文档就绪时首先声明全局变量drawerIsUp = false;,检查它是否为false或者然后执行滚动部分。但是,由于当drawer上升window.pageYOffset0时,如果用户尝试滚动top样式,我怎样才能继续为div window.pageYOffset样式添加像素1}}已经0了?

    $(document).ready(function (){
    drawerDiv = this.getElementById("drawer");
    topBar = this.getElementById("top-bar");
    drawerIsUp = false;


    scrollDrawer = function () {
      if (drawerIsUp) {
  console.log('entered');
        function winScroll() {
           drawerDiv.style.top = window.pageYOffset + "px";
        }
          winScroll();
          $(window).bind({scroll: winScroll});
      }
    }

});

这是html:

         <div id="app">
            <div id="bg">
            </div>

              @section('topBar')
                @include('customer.layouts.partials.top-bar')
              @show
            <div id="main-section">
              @section('header')
                @include('customer.layouts.partials.header')
              @show

              @section('carousel')
                @include('customer.layouts.partials.carousel', ['function' => 'drawer', 'carouselPadding' => ''])
              @show
            </div>

            <div id="drawer">
              <div id="magazine-detail">
              </div>
              <div id="magazine-detail-carousel">
                @section('magazine-detail-carousel')
                  @include('customer.layouts.partials.carousel', ['function' => 'magazineDetail', 'carouselPadding' => 'carouselPadding'])
                @show
              </div>
            </div>

          </div>

因此,抽屉在点击时越过main-section,然后当它结束时我应该向下移动它,如果用户向上滚动它。

抽屉和顶栏的css:

#main-section {
  height: calc(100vh - 92px);
  overflow-y: scroll;
  width: 100%;
  position: fixed;
  overflow-y: scroll;
  top:77px;
}

#drawer {
  z-index: 5;
  position: fixed;
  top: 100vh;
  height: calc(100vh - 92px);
  max-height: 100%;
  overflow-y: scroll;
  width: 100%;
  background-color: $white;
  padding-left: 15px;
  padding-right: 15px;
}

.top-bar {
  position: fixed;
  top: 0;
}

1 个答案:

答案 0 :(得分:0)

您在drawer函数中使用了winResize。但是在drawer内宣布$(document).ready,因此winResize无法识别drawer的含义。

$(document).ready(function (){
    drawer = this.getElementById("drawer");
    topBar = this.getElementById("top-bar");
    drawerIsUp = false;

    function winResize() {
       drawer.style.top = topBar.offsetHeight + "px";
    }

    winResize();
    $(window).bind({resize: winResize, scroll: winScroll});
});

详细了解变量范围

https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/