简体   繁体   English

相对于页面上滚动位置的可视计数器

[英]Visual counter relative to scroll position on page

For a project i have to make a visual counter with html and javascript that counts down from 150 to 0 relative to the scrolling position of the window. 对于一个项目,我必须创建一个带有html和javascript的可视计数器,相对于窗口的滚动位置,该计数器从150向下计数到0。

I'm not entirely sure how i should go about doing this but here's what i have so far: 我不完全确定该怎么做,但是到目前为止,这是我所拥有的:

HTML: HTML:

<span class="meterCounter">
    <label class="number">150</label>
    <label class="rotated">mtr.</label>
</span>  

JS: JS:

// calculate page height (keeping element position in mind):
var offset = $(".meterCounter").offset().top;
var pageHeight = $(document).height() - offset;

// calculate how many pixels user should scroll until html changes:
var divide = pageHeight / 150;

count = 150;

$(document).scroll(function(){

    var scrollPosition = $(window).scrollTop();

    // (magic if statement here that determines when html should change)

        count--;
        $(".number").html(count);
        divide = divide + divide;


});

JSfiddle here of what i have atm (by DelightedD0D, thanks btw!) JSfiddle在这里介绍我拥有的atm(由DelightedD0D表示感谢,谢谢!)

I've searched around the interwebs but can't find a good solution to this little problem here. 我已经搜索了互连网,但是在这里找不到解决这个小问题的好方法。

Help and advice on how to solve this mystery is much appreciated! 非常感谢您提供有关如何解开这个谜团的帮助和建议!

(note: not asking for people to write code for me, just some solid advice or a push in the right direction! :] ). (注意:不是要求人们为我编写代码,只是一些可靠的建议或朝正确方向的推动!:])。

Thanks alot! 非常感谢!

*edit: *编辑:
i should add, at the bottom of the page the counter needs to be at 0 and at the top it needs to be back to 150, so, in my mind i have to update the html each time i scroll X amount of pixels (X being the "divide" variable). 我应该添加,页面底部的计数器需要为0,顶部需要返回为150,因此,在我看来,每次滚动X像素数量(X时,我都必须更新html是“ divide”变量)。

Actually @Gaby aka G. Petrioli answer is a bit flawed. 实际上,@ Gaby aka G. Petrioli的回答有点瑕疵。 Value in variable pageHeight shouldn't be reduced by counter's distance from the top of the document, which is stored in variable offset . 不应将变量pageHeight值减小计数器到文档顶部的距离,该距离存储在变量offset You can observe the resulting erroneous behavior, by changing counter's position, removing Math.round() (so that the error is not covered by approximation) and scrolling to the bottom. 您可以通过更改计数器的位置,删除Math.round() (从而使误差不被近似值覆盖)并滚动到底部来观察由此产生的错误行为。 Or just see it in action right now. 或立即查看实际效果 (fixed). (固定)。

Here is my solution using plain JavaScript. 这是我使用普通JavaScript的解决方案。 It includes recalculation on window's resize, too. 它还包括对窗口大小的重新计算。

 var counter = document.getElementById('counter'); function updateCounter() { 'use strict'; var height = document.documentElement.scrollHeight - window.innerHeight; counter.textContent = 150 - document.documentElement.scrollTop / height * 150; } document.addEventListener('scroll', updateCounter); window.addEventListener('resize', updateCounter); 
 html, body { height: 1000%; } #counter { position: fixed; } 
 <span id="counter">150</span> 

( See it on JSFiddle ). 在JSFiddle上查看 )。

Few notes on why this JavaScript looks the way it looks: 关于此JavaScript外观的一些注释:

  • 'use strict' is to opt into so called strict mode (MDN). 'use strict'是选择进入所谓的严格模式 (MDN)。
  • document.documentElement.scrollHeight - window.innerHeight is height that we are interested in. It is height of the entire document reduced by the height of viewport. document.documentElement.scrollHeight - window.innerHeight是我们感兴趣的高度。它是整个文档的高度,减去视口的高度。 Why do we need that reduction? 为什么我们需要减少呢? Because whatever is our current scroll position, we will never scroll completely out of document, ie we will always see some portion of it and that portion equals viewport's height. 因为无论当前滚动位置是什么,我们都不会完全滚动出文档,即,我们将始终看到文档的某些部分,并且该部分等于视口的高度。

    Another thing: It is stored in variable for readability, but in fact it could be put in place of height in the next line, as that is its only appearance. 另一件事:为了便于阅读,将其存储在变量中,但实际上,可以将它放在下一行的height位置,因为这是它的唯一外观。
  • document.documentElement.scrollTop / height will give us our scroll position relatively to document's height, ie how many percent of document we have scrolled. document.documentElement.scrollTop / height将为我们提供相对于文档高度的滚动位置,即我们已滚动了多少百分比的文档。 It will be number in range from 0 to 1, but we are interested in range from 0 to 150, hence multiplying. 它将是介于0到1之间的数字,但我们对介于0到150之间的范围感兴趣,因此会相乘。 And all of that is subtracted from 150, because we want to count from 150 to 0, not the opposite. 所有这些都从150中减去,因为我们想从150计数到0,而不是相反。
  • If you want counter to display only integers, put the whole statement after counter.textContent = inside Math.round() . 如果要让计数器仅显示整数,请将整个语句放在Math.round()内部的counter.textContent =之后。
  • The two last lines attach function that updates counter to events of scroll and resize. 最后两行附加了更新滚动和调整大小事件计数器的功能。 That way, whenever we scroll or resize window, counter-updating function will be invoked. 这样,每当我们滚动或调整窗口大小时,都会调用反更新功能。

I personally find this approach much clearer from the jQuery one that was posted here. 我个人从此处发布的jQuery中发现这种方法更加清晰。 And it has better performance too, of course. 当然,它也具有更好的性能。

UPDATE : Changed two occurrences of document.body to document.documentElement , because the manner in which at least one of them was used here was deprecated and stopped working. 更新 :将两个出现的document.body更改为document.documentElement ,因为不推荐使用其中至少一个的使用方式并停止工作。

Expanding on my comment that you need to calculate where the scrollPosition is relative to the total height 扩展我的评论,您需要计算scrollPosition相对于总高度的位置

A sample 一个样品

// calculate page height (keeping element position in mind):
var offset = $(".meterCounter").offset().top;
var pageHeight = $(document).height() - $(window).height();

// calculate how many pixels user should scroll until html changes:
var count = 150,
    divide = pageHeight / count;

$(document).scroll(function(e){
    var scrollPosition = $(window).scrollTop(),
        relevantToHeight = scrollPosition*count/pageHeight ;

    // (magic if statement here that determines when html should change)
    $(".number").html(count - Math.round(relevantToHeight));
});

Demo at https://jsfiddle.net/gaby/d160vLqm/18/ 演示在https://jsfiddle.net/gaby/d160vLqm/18/

( keep in mind that on window resize you need to recalculate most of the cached variables ) 请记住,在调整窗口大小时,您需要重新计算大多数缓存的变量

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

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