2016-10-27 16 views
1

我有一個div在頁面加載時被推下來,然後被暴露出來,然後被推到top-bar並接管屏幕上的其餘部分通過改變頂部的風格在我的功能這樣的點擊功能:Javascript - 在window.pageYOffset已經爲0時檢測滾動嘗試

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

我想,當該div可見,檢測用戶是否滾動起來,當它試圖使DIV滑下向上滾動按照用戶滾動的像素量。我不知道如何確切地做到這一點。

在我的腳本scroll-event.js我試圖設置一個函數,我將在文檔準備好首先聲明全局變量drawerIsUp = false;,檢查它是否爲假或真,然後執行滾動部分。但是,因爲drawerwindow.pageYOffset0,如果用戶試圖滾動但window.pageYOffset已0123?如何可以添加像素到div top樣式?

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

回答

0

您使用drawerwinResize功能。但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/

+0

像你這樣的建議,但我仍然得到一個錯誤,我已經改變了代碼。我用新代碼更新了我的問題 – Leff

+0

它現在起作用了,函數和一個變量具有相同的名稱抽屜,這就是錯誤。但是滾動事件沒有任何反應。 Div不下滑。 – Leff