jQuery scrollTop()位置为百分比

时间:2015-01-20 18:03:23

标签: javascript jquery scrolltop

<script>
document.getElementById('listen-btn').addEventListener('click', function() {
    document.getElementById('music-player').play();
});

<script>
    $(window).scroll(function() {
        if($(window).scrollTop() > 1400)
        document.querySelector('#music-player').pause();
    });
</script>

按钮启动音频播放器并滚动到音频播放器可见的部分。当您滚动下一部分时,音频播放器会在您滚动1400后停止,但我需要它是相对的。如何让1400百分比(50%)

2 个答案:

答案 0 :(得分:7)

这是可能的 - 一些算术将完成这项工作。诀窍是使用$(document).height()检索页面高度。如果您正在引用视口高度,则需要使用$(window).height()

$(window).scroll(function() {
    if($(window).scrollTop() > $(document).height()*0.5)
    document.querySelector('#music-player').pause();
});

答案 1 :(得分:2)

尝试使用此代码:

$(window).on('scroll', function() {
   var st = $(this).scrollTop();
   var wh = $(document).height();

// st : wh = X : 100
// x = (st*100)/wh

var perc = (st*100)/wh

// Your percentage is contained in perc variable

console.log('The percentage is '+perc);

});