簡體   English   中英

Javascript - 當window.pageYOffset已經為0時檢測滾動嘗試

[英]Javascript - detecting scroll attempt when window.pageYOffset is already 0

我有一個div在頁面加載下推出視圖,然后稍后暴露並推到top-bar並通過更改我的函數中的頂部樣式接管單擊功能的屏幕的其余部分,如下所示:

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

我希望當div可見時,檢測用戶是否向上滾動,當它嘗試向上滾動時,div向下滑動用戶向上滾動的像素數量。 我不確定如何做到這一點。

在我的腳本scroll-event.js我試圖設置一個函數,我將文件就緒,首先聲明全局變量drawerIsUp = false; ,檢查它是否為false或true然后執行滾動部分。 但是,因為當drawer是向上window.pageYOffset0 ,我怎能添加像素到div top的風格,如果用戶試圖滾動,但window.pageYOffset0了嗎?

    $(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;
}

你在winResize函數中使用了drawer 但是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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM