Javascript中确定垂直滚动百分比的跨浏览器方法 [英] Cross-Browser Method to Determine Vertical Scroll Percentage in Javascript

查看:14
本文介绍了Javascript中确定垂直滚动百分比的跨浏览器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何找出用户在任何给定点移动过的垂直滚动条的百分比?

How can I find out what percentage of the vertical scrollbar a user has moved through at any given point?

很容易在用户向下滚动页面时触发 onscroll 事件,但是我如何在该事件中找出他们滚动了多远?在这种情况下,百分比尤其重要.我不是特别担心 IE6 的解决方案.

It's easy enough to trap the onscroll event to fire when the user scrolls down the page, but how do I find out within that event how far they have scrolled? In this case, the percentage particularly is what's important. I'm not particularly worried about a solution for IE6.

是否有任何主要框架(Dojo、jQuery、Prototype、Mootools)以简单的跨浏览器兼容方式公开了这一点?

Do any of the major frameworks (Dojo, jQuery, Prototype, Mootools) expose this in a simple cross-browser compatible way?

推荐答案

2016 年 10 月:已修复.答案中缺少 jsbin 演示中的括号.糟糕.

Oct 2016: Fixed. Parentheses in jsbin demo were missing from answer. Oops.

Chrome、火狐、IE9+.jsbin 现场演示

var h = document.documentElement, 
    b = document.body,
    st = 'scrollTop',
    sh = 'scrollHeight';

var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;

作为函数:

function getScrollPercent() {
    var h = document.documentElement, 
        b = document.body,
        st = 'scrollTop',
        sh = 'scrollHeight';
    return (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
}

如果你更喜欢 jQuery(原始答案):

If you prefer jQuery (original answer):

$(window).on('scroll', function(){
  var s = $(window).scrollTop(),
      d = $(document).height(),
      c = $(window).height();

  var scrollPercent = (s / (d - c)) * 100;
  
  console.clear();
  console.log(scrollPercent);
})

html{ height:100%; }
body{ height:300%; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于Javascript中确定垂直滚动百分比的跨浏览器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆