【问题标题】:How to get horizontal scrolling percentage of an HTML element in JavaScript?如何在 JavaScript 中获取 HTML 元素的水平滚动百分比?
【发布时间】:2012-08-31 20:59:15
【问题描述】:

我们如何计算滚动条在起点和终点之间覆盖的“距离”百分比?

<div id="container" style="overflow-x:scroll; max-width:1000px;">
  <div id="contained" style="width:3000px;"></div>
</div>

<script>
  $('#container').scroll(function(){
    var scrollPercentage; //How to get scroll percentage?
  });
</script>

所以,如果滚动条完全在左边,我们想得到0,如果它完全在右边,我们想得到100

【问题讨论】:

    标签: javascript jquery html scroll


    【解决方案1】:
    var scrollPercentage = 100 * this.scrollLeft / (this.scrollWidth-this.clientWidth); 
    

    http://jsfiddle.net/vWDfb/3/

    或者,如果你真的必须使用 jQuery:

    scrollPercentage = 100 * $(this).scrollLeft() / ($('#contained').width() - $(this).width());
    

    http://jsfiddle.net/vWDfb/5/

    【讨论】:

      【解决方案2】:

      在这里查看:http://jsfiddle.net/vWDfb/1/

      $('#container').scroll(function(){
          var scrollPercentage = 100*this.scrollLeft/this.scrollWidth/(1-this.clientWidth/this.scrollWidth);
      });
      

      将这个数字四舍五入到例如两位小数会很有用。然后,使用

      scrollPercentage.toFixed(2);
      

      编辑:更好用

      var scrollPercentage = 100 * this.scrollLeft / (this.scrollWidth-this.clientWidth); 
      

      正如@Blazemonger 指出的那样。

      【讨论】:

        猜你喜欢
        • 2021-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多