如何在JavaScript中获取HTML元素的水平滚动百分比? [英] How to get horizontal scrolling percentage of an HTML element in JavaScript?
本文介绍了如何在JavaScript中获取HTML元素的水平滚动百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< p>< p>< p>< p>< ; div id =containerstyle =overflow-x:scroll; max-width:1000px;>
< div id =containedstyle =width:3000px;>< / div>
< / div>
< script>
$('#container')。scroll(function(){
var scrollPercentage; //如何获得滚动百分比?
});
< / script>
因此,如果滚动条完全位于左侧,我们希望得到 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屋!
查看全文