2017-12-18 193 views
2

我想記錄用戶滾動包裝的程度。使用scrollTop檢測滾動

以下代碼不起作用。 我想知道我做錯了什麼,以及如何解決它。謝謝!

const content = document.getElementById('content') 
const wrapper = document.getElementById('wrapper').addEventListener('scroll',() => { 
    console.log(content.scrollTop) 
})
#wrapper { 
 
    background-color: red; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    width: 250px; 
 
    height: 250px; 
 
    overflow: auto; 
 
} 
 

#content { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    background-color: orange; 
 
    width: 50px; 
 
    height: 500px; 
 
}
<div id="wrapper"> 
 
    <div id="content"></div> 
 
</div>

+0

包裝是具有不滾動的內容,所以它是總是會變成零。 –

+0

好的謝謝,多少包裝正在滾動? – Radex

回答

0

獲取匹配元素集中第一個元素的滾動條的當前垂直位置或爲每個匹配元素設置滾動條的垂直位置。

scrollTop():垂直滾動位置與在可滾動區域上方隱藏的像素數量相同。如果滾動條是在最高層,或者如果元素不是滾動的,這個數目將是0。

$('#wrapper').scroll(function() { 
 
    console.log($(this).scrollTop()); 
 
});
#wrapper { 
 
    background-color: red; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    width: 250px; 
 
    height: 250px; 
 
    overflow: auto; 
 
} 
 

 
#content { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    background-color: orange; 
 
    width: 50px; 
 
    height: 500px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="wrapper"> 
 
    <div id="content"></div> 
 
</div>