如何应用document.height / window.height的比例,范围从1到100。

时间:2014-09-19 11:41:23

标签: javascript jquery css

我想使用高度为110px和10px的两个div来制作滚动条。较小的一个在最高的一个里面。这让我有空间将较小的边缘高度从0改为100px,它仍然适合较高的边缘高度。

如果你想知道,0到100px是我在问题标题上的意思,通过拟合从1到100的等级。

我现在要做的是弄清楚如何计算比率,以使我的10px高度位置相对于较高的div与document.height比率与window.height成比例。

我整晚都在试验,但没有任何功能。以下是我所拥有的一些代码,但是我删除了所有与我在这里提问的相关内容,因为我想听听纯粹的想法。

请建议。

var wheight = $(window).height();
var dheight = $(document).height();
document.getElementById("wheight").innerHTML=wheight;
document.getElementById("dheight").innerHTML=dheight;
document.getElementById("sidescrollbtn").style.marginTop = '70px';

http://jsfiddle.net/vinicius5581/2y63xnxa/4/

1 个答案:

答案 0 :(得分:0)

计算百分比非常简单。 然后将百分比缩放到滚动条的大小是微不足道的。

        var offset = $(window).scrollTop();
        $(window).scrollTop(offset + 20);  
        var wheight = $(window).height();
        var dheight = $(document).height();

        //yep, this is all there is to it.
        var percentualOffset = (offset / wheight) * 100;

        //or use dheight. i'm not sure which applies to you
        //var percentualOffset = (offset / dheight) * 100;

        $("#sidescrollbtn").css("top", percentualOffset);

有关正常工作的实施,请参阅http://jsfiddle.net/2y63xnxa/9/