JS - 获取Viewport中元素的百分比

时间:2013-11-26 16:56:26

标签: javascript jquery scroll viewport offset

我希望在视口中获得元素(div)的百分比。

  • 当元素进入视口时,我希望值为0。
  • 当元素和元素的高度离开视口时,我希望值为100。

以下是我想要做的http://imgur.com/2ZPpps5

的5个视口

我试过了:

$(window).bind('scroll',function(){
var  viewportHeight = $(window).height(),
elementOffsetTop = $('#element').offset().top,
elementHeight = $('#element').height();

var numerator = 200 * (window.pageYOffset-elementOffsetTop+viewportHeight);
var denominator = (elementOffset+elementHeight+viewportHeight);
console.log(numerator/denominator);
});

此代码有效。 (我不明白为什么我要乘以2)。

但是当我调整页面大小时,这段代码不起作用(值介于0到85之间......)

想法?

2 个答案:

答案 0 :(得分:8)

http://jsfiddle.net/nate/4N3Pj/1/

var $element = $('#element');
var $win = $(window);
var $vis = $('#visible');

$win.on('scroll', function () {
    console.log(percentageSeen());
    $vis.text(percentageSeen() + '%');
});

function percentageSeen () {
    var viewportHeight = $(window).height(),
        scrollTop = $win.scrollTop(),
        elementOffsetTop = $element.offset().top,
        elementHeight = $element.height();


    if (elementOffsetTop > (scrollTop + viewportHeight)) {
        return 0;
    } else if ((elementOffsetTop + elementHeight) < scrollTop) {
        return 100;
    } else {
        var distance = (scrollTop + viewportHeight) - elementOffsetTop;
        var percentage = distance / ((viewportHeight + elementHeight) / 100);
        percentage = Math.round(percentage);
        return percentage;
    }
}

$win.trigger('scroll');

答案 1 :(得分:0)

我的版本略有不同。当元素高于屏幕高度本身时,它将在视口中解释为100%。

例如,如果屏幕高度为1000像素,元素为2000像素高度,并且完全滚动到视图中,则该函数将返回100%,而不是正常的50%。

享受。

var percentWithinViewport = function (element) {

    var elementTop = element.offset().top;
    var scrollTop = $(window).scrollTop();
    var spaceTop = elementTop - scrollTop;
    var elementHeight = element.height();
    var screenHeight = $(window).height();
    var scrollBottom = scrollTop + screenHeight;
    var bottomElement = elementTop + element.height();
    var spaceBottom = bottomElement - scrollBottom;
    var heightInScreen = elementHeight - spaceBottom;
    var percentage;

    if (spaceTop < 0) {
        heightInScreen -= spaceTop * -1;
    }

    if (spaceBottom < 0) {
        heightInScreen -= spaceBottom * -1;
    }

    percentage = heightInScreen / screenHeight * 100;
    percentage = percentage < 0 ? 0 : percentage;

    element.attr('data-percent-viewport', percentage);

    return percentage;
};