仅在使用javascript滚动页面25%时获得警报

时间:2019-06-06 11:31:12

标签: javascript

我试图在页面分别滚动25%和50%时显示和提醒。

这是我的代码,它工作正常,但未显示警报。

//Get the scroll page percentage
function getHeight() {
    var D = document;
    return Math.max(
        D.body.scrollHeight, D.documentElement.scrollHeight,
        D.body.offsetHeight, D.documentElement.offsetHeight,
        D.body.clientHeight, D.documentElement.clientHeight
    )
}

var docheight = getHeight();
function amountScrolled(){
    var winheight= window.innerHeight || (document.documentElement || document.body).clientHeight
    var docheight = getHeight()
    var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop
    var trackLength = docheight - winheight
    var pageScrolled = Math.floor(scrollTop/trackLength * 100) // gets percentage scrolled (ie: 80 or NaN if tracklength == 0)
    //console.log(pageScrolled + '% scrolled');
    document.getElementById('percentage').innerHTML = 'Page scroll percentage: ' + pageScrolled + '% scrolled';

    if(pageScrolled === Math.floor(scrollTop/trackLength * 25)) {
      alert('25%');
    }

}

window.addEventListener("scroll", function(){
    amountScrolled()
}, false)

有人可以帮我这个忙吗?

预先感谢

2 个答案:

答案 0 :(得分:0)

更改以下代码

if(pageScrolled === Math.floor(scrollTop/trackLength * 25)) {
      alert('25%');
}

if(pageScrolled === 25) {
      alert('25%');
}

它将起作用。

答案 1 :(得分:0)

您的评论说:

var pageScrolled = ... // gets percentage scrolled (ie: 80 or NaN if tracklength == 0)

所以pageScrolled包含从0到100的百分比。那么为什么要在if中将百分比与Math.floor(scrollTop/trackLength * 25)进行比较?

不是pageScrolled === 25吗?

让我重构您的代码:

function getTrackLength() {
  const { body, documentElement } = document;
  const winheight = window.innerHeight || (documentElement || body).clientHeight
  const docheight = Math.max(
      body.scrollHeight, documentElement.scrollHeight,
      body.offsetHeight, documentElement.offsetHeight,
      body.clientHeight, documentElement.clientHeight
  );

  return docheight - winheight;
}

function getScrollTop() {
  return window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
}

let previousValue = 0;

function checkScroll() {
  const trackLength = getTrackLength();
  const scrollTop = getScrollTop();
  const percent = Math.floor(scrollTop / trackLength * 100) 

  console.log({ percent, previousValue });

  if (percent >= 25 && previousValue < 25) {
    console.log('Just passed 25%');
  } else if (percent >= 50 && previousValue < 50) {
    console.log('Just passed 50%');
  }

  previousValue = percent;
}

window.addEventListener("scroll", checkScroll, false);

即使滚动从24%变为26%,此新代码段也将触发,因为它存储的是最后一个滚动位置并将其与当前滚动位置进行比较。