如何在 JavaScript 中获取 HTML 元素的水平滚动百分比?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12222389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:25:56  来源:igfitidea点击:

How to get horizontal scrolling percentage of an HTML element in JavaScript?

javascriptjqueryhtmlscroll

提问by Oriol

How can we calculate the percentage of 'distance' covered by the scrollbar on an element between start and end?

我们如何计算开始和结束之间元素上滚动条覆盖的“距离”百分比?

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

So, if the scrollbar is completely at the left we want to get 0, and if it's completely at the right we want to get 100.

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

回答by Blazemonger

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

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

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

Or, if you really must use jQuery:

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

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

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

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

回答by Oriol

See it here: http://jsfiddle.net/vWDfb/1/

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

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

It can be useful to round that number to, for example, two decimals. Then, use

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

scrollPercentage.toFixed(2);


Edit: Better use

编辑:更好地使用

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

as @Blazemonger pointed out.

正如@Blazemonger 指出的那样。