![](/img/trans.png)
[英]Calling a function in javascript when the height of a div reaches certain pixel
[英]How to trigger a JavaScript function when the scroll bar reaches a certain percentage of the page height
我正在尋找用純JavaScript編寫的解決方案,該解決方案會在頁面滾動的一定百分比(例如80%)上觸發JS函數。 我正在尋找無需750行代碼或使用jQuery即可完成與Waypoint相似的工作。
我假設我將確定窗口的高度,然后在滾動點大於高度的80%時觸發回調。
這里的其他要求是我只希望它觸發一次。 我還關心的另一個問題是不斷輪詢滾動百分比的潛在性能問題。 這是一個有效的問題嗎?
您可以使用onscroll
函數trigerScroll(ev){if(window.pageYOffset> 400)alert('用戶已滾動至少400 px!'); } window.onscroll = trigerScroll;
編輯:
您可以像這樣獲取文檔高度
var body = document.body,
html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
一種在滾動時每500ms檢查一次頁面滾動的方法,並且只會運行一次:
var throttledListener = throttle(scrollListener, 500); window.addEventListener('scroll', throttledListener); function throttle(func, delay) { // allows [func] to run once every [delay] ms var func = func.bind(func), last = Date.now(); return function() { if (Date.now() - last > delay) { func(); last = Date.now(); } } } function scrollListener() { console.log('scrolled'); var threshold = document.body.clientHeight * 0.6; if (window.pageYOffset >= threshold) { alert('user scrolled to threshold; listener removed'); window.removeEventListener('scroll', throttledListener); } }
<div style="height:2000px;width:100%">tall div</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.