javascript jQuery scrollTop() 位置到百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28052165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery scrollTop() position to percentage
提问by Peyton Gregory
<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. How to I make the 1400 a percentage (50%)
该按钮启动音频播放器并滚动到音频播放器可见的部分。当你滚动下一部分时,一旦你滚动了 1400,音频播放器就会停止,但我需要它是相对的。如何使 1400 成为百分比 (50%)
回答by Terry
That is possible — some arithmetic will do the job. The trick is to retrieve the page height using $(document).height()
. If you're referring to the viewport height though, then you will need to use $(window).height()
.
这是可能的——一些算术可以完成这项工作。诀窍是使用 检索页面高度$(document).height()
。如果您指的是视口高度,那么您将需要使用$(window).height()
.
$(window).scroll(function() {
if($(window).scrollTop() > $(document).height()*0.5)
document.querySelector('#music-player').pause();
});
回答by derogab
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);
});