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

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

问题描述

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



将'onscroll'事件捕获到以下是很容易的当用户向下滚动页面时触发,但如何在该事件中找出它们滚动了多远?在这种情况下,特别是百分比是重要的。我并不特别担心IE6的解决方案。



任何主要框架(Dojo,jQuery,Prototype,Mootools)都是在一个简单的跨浏览器中公开的兼容方式?



干杯,

解决方案


2016年10月:已修复。 jsbin演示中的括号在答案中丢失了。 糟糕。




Chrome,Firefox,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 (原始答案):



  $(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%;身体{身高:300%; }  

 < script src =https:// ajax .googleapis.com / AJAX /库/ jquery的/ 2.1.1 / jquery.min.js>< /脚本>  


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

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.

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

Cheers,

解决方案

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

Chrome, Firefox, IE9+. Live Demo on 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;

As function:

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;
}

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天全站免登陆