For cross-browser compatibility in determining the percentage of vertical scroll completed, a versatile method is required. While frameworks like Dojo, jQuery, Prototype, and Mootools may offer solutions, we will delve into a native JavaScript approach.
Using the 'scrollTop' and 'scrollHeight' properties, we can calculate the scroll percentage as follows:
<code class="javascript">var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight'; var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;</code>
This method effectively determines the scroll percentage in all major browsers, including Chrome, Firefox, and IE9 .
While the native solution is efficient, we also provide the jQuery implementation from the original answer:
<code class="javascript">$(window).on('scroll', function(){ var s = $(window).scrollTop(), d = $(document).height(), c = $(window).height(); var scrollPercent = (s / (d - c)) * 100; });</code>
It is important to note that the method provided may not reach 100% accuracy on modern mobile browsers due to UI autohide-on-scroll behavior. However, for most scenarios, it should provide a reliable approximation of the scroll percentage across various browsers.
The above is the detailed content of How to Calculate Scroll Percentage in JavaScript for Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!