onscroll 事件和onScrollCapture事件

drunk喵咪發表於2020-11-24

onscroll 事件在元素滾動條在滾動時觸發。

HTML:
<element onscroll="myScript">
JavaScript 中:
object.onscroll=function(){myScript};

JavaScript 中, 使用 addEventListener() 方法:
object.addEventListener("scroll", myScript);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<style>
div {
    border: 1px solid black;
    width: 200px;
    height: 100px;
    overflow: scroll;
}
</style>
</head>
<body>

<p>嘗試滾動 div。</p>
<div onscroll="myFunction()">In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'</div>
<p>滾動 <span id="demo">0</span> 次。</p>
<script>
x = 0;
function myFunction() {
    document.getElementById("demo").innerHTML = x += 1;
}
</script>

</body>
</html>

在這裡插入圖片描述
onScrollCapture 監聽滑鼠滾動

const onScroll = (e) => {
        // console.log("onScroll", e.target.scrollTop);
        if (e.target.scrollTop == 0 && !loading) {
            console.info('到頂');
            e.target.scrollTop = 10;
            onLoad(selectTime, minPage - 1);
        }
        else if (e.target.scrollTop + e.target.clientHeight == e.target.scrollHeight && !loading) {
            console.info('到底');
            onLoad(selectTime, maxPage + 1);
        }
    }
<div style={{ height: "532px" }} onScrollCapture={onScroll}></div>

相關文章