简体   繁体   English

jQuery scrollTop()位置为百分比

[英]jQuery scrollTop() position to percentage

<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>

The button starts the audio player and scrolls to the section where the audio player is visible. 该按钮启动音频播放器并滚动到音频播放器可见的部分。 When you scroll the the next section the audio player stops once you've scrolled 1400 but I need that to be relative. 当您滚动下一部分时,音频播放器会在您滚动1400后停止,但我需要它是相对的。 How to I make the 1400 a percentage (50%) 如何让1400百分比(50%)

That is possible — some arithmetic will do the job. 这是可能的 - 一些算术将完成这项工作。 The trick is to retrieve the page height using $(document).height() . 诀窍是使用$(document).height()检索页面高度。 If you're referring to the viewport height though, then you will need to use $(window).height() . 如果您指的是视口高度,那么您将需要使用$(window).height()

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

Try to use this code: 尝试使用此代码:

$(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);

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM