如何在 JavaScript 中获取 HTML 元素的水平滚动百分比? [英] How to get horizontal scrolling percentage of an HTML element in JavaScript?
本文介绍了如何在 JavaScript 中获取 HTML 元素的水平滚动百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们如何计算元素上滚动条在开始和结束之间覆盖的距离"百分比?
<div id="container" style="overflow-x:scroll; max-width:1000px;"><div id="contained" style="width:3000px;"></div>
<脚本>$('#container').scroll(function(){变量滚动百分比;//如何获取滚动百分比?});
所以,如果滚动条完全在左边,我们希望得到 0
,如果它完全在右边,我们希望得到 100
.
解决方案
var scrollPercentage = 100 * this.scrollLeft/(this.scrollWidth-this.clientWidth);
或者,如果你真的必须使用 jQuery:
scrollPercentage = 100 * $(this).scrollLeft()/($('#contained').width() - $(this).width());
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
.
解决方案
var scrollPercentage = 100 * this.scrollLeft / (this.scrollWidth-this.clientWidth);
Or, if you really must use jQuery:
scrollPercentage = 100 * $(this).scrollLeft() / ($('#contained').width() - $(this).width());
这篇关于如何在 JavaScript 中获取 HTML 元素的水平滚动百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文