Last active
December 4, 2018 13:18
-
-
Save fergusKe/771e29e218fc34c2619c2a19eb4e9ff5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function scrollRatio(percentage) { | |
var domHeight = Math.max( | |
document.body.scrollHeight, | |
document.body.offsetHeight, | |
document.documentElement.clientHeight, | |
document.documentElement.scrollHeight, | |
document.documentElement.offsetHeight); | |
return parseInt(window.scrollY / (domHeight - window.innerHeight) * 100 / percentage) * percentage || 0; | |
} | |
// jQ 版 | |
function scrollRatio(percentage){ | |
var winheight = $(window).height(); | |
var docheight = $(document).height(); | |
var scrollTop = $(window).scrollTop(); | |
var trackLength = docheight - winheight; | |
return parseInt(scrollTop / trackLength * 100 / percentage) * percentage; | |
} | |
// js 版 v2 | |
function getDocHeight() { | |
var D = document; | |
return Math.max( | |
D.body.scrollHeight, D.documentElement.scrollHeight, | |
D.body.offsetHeight, D.documentElement.offsetHeight, | |
D.body.clientHeight, D.documentElement.clientHeight | |
) | |
} | |
function amountscrolled(){ | |
var winheight= window.innerHeight || (document.documentElement || document.body).clientHeight | |
var docheight = getDocHeight() | |
var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop | |
var trackLength = docheight - winheight | |
var pctScrolled = Math.floor(scrollTop/trackLength * 100) // gets percentage scrolled (ie: 80 or NaN if tracklength == 0) | |
console.log(pctScrolled + '%') | |
} | |
window.addEventListener("scroll", function(){ | |
amountscrolled() | |
}, false) | |
// js 版 v3 | |
var winheight, docheight, trackLength, throttlescroll | |
function getmeasurements(){ | |
winheight= window.innerHeight || (document.documentElement || document.body).clientHeight | |
docheight = getDocHeight() | |
trackLength = docheight - winheight | |
} | |
function amountscrolled(){ | |
var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop | |
var pctScrolled = Math.floor(scrollTop/trackLength * 100) // gets percentage scrolled (ie: 80 or NaN if tracklength == 0) | |
console.log(pctScrolled + '% scrolled') | |
} | |
getmeasurements() | |
window.addEventListener("resize", function(){ | |
getmeasurements() | |
}, false) | |
window.addEventListener("scroll", function(){ | |
clearTimeout(throttlescroll) | |
throttlescroll = setTimeout(function(){ // throttle code inside scroll to once every 50 milliseconds | |
amountscrolled() | |
}, 50) | |
}, false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment