簡體   English   中英

如何檢測是否在某個元素內發生滾動

[英]how to detect if scroll is happening within certain element

我想檢測指針滾動是否發生在某個元素內,然后執行某些操作。 我已經嘗試過這段代碼,但它似乎不起作用:

var lastScrollTop = 0;
    $(".class-name").scroll(function(event){
       var st = $(this).scrollTop();
       if (st > lastScrollTop){
           console.log("scroll down");
       } else {
          console.log("scroll up");
       }
       lastScrollTop = st;
    });

你能幫我理解我做錯了什么嗎?

謝謝!

編輯:

scrollTop為您提供非頁面元素滾動條的當前 position。
因此,如果他沒有滾動條,它將為 0。:

或者如果元素不可滾動,則此數字將為 0。

如果元素沒有滾動條,則.scroll()也一樣,它將永遠不會發生。

 var lastScrollTop = 0; $(".class-name").scroll(function(event){ var st = $(this).scrollTop(); if (st > lastScrollTop){ console.log("scroll down"); } else { console.log("scroll up"); } lastScrollTop = st; });
 .class-name{ width:100px; height:200px; overflow:auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="class-name">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>

暫無
暫無

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

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