当页面仅使用javascript滚动25%时获取警报
我试图在页面分别滚动25%和50%时显示和提醒 这是我的代码,工作正常,但没有显示警报当页面仅使用javascript滚动25%时获取警报,javascript,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
//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)
有人能帮我吗?我怎样才能做到
提前感谢更改以下代码
if(pageScrolled === Math.floor(scrollTop/trackLength * 25)) {
alert('25%');
}
到
它会起作用的。你的评论说:
var pageScrolled = ... // gets percentage scrolled (ie: 80 or NaN if tracklength == 0)
所以pageScrolled包含百分比,从0到100。那么,为什么要将百分比与if中的Math.floorscrollTop/trackLength*25进行比较
它不应该被翻页===25吗
让我重构您的代码:
函数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
;
返回八-winheight;
}
函数getScrollTop{
return window.pageYOffset | | | | document.documentElement | | document.body.parentNode | | document.body.scrollTop;
}
设previousValue=0;
功能检查卷轴{
const trackLength=getTrackLength;
const scrollTop=getScrollTop;
常数百分比=Math.floorscrollTop/轨道长度*100
console.log{percent,previousValue};
如果百分比>=25&&previousValue<25{
日志“刚刚超过25%”;
}否则,如果百分比>=50&&previousValue<50{
console.log“刚刚超过50%”;
}
以前的值=百分比;
}
window.addEventListenerscroll、checkScroll、false;
即使滚动从24%移动到26%,这个新代码段也会触发,因为它存储了最后一个滚动位置并将其与当前位置进行比较 你得到的错误是什么?可能是你的情况永远都不是真的。例如,你可以从24%跳到26%,你的数学计算x*25是错误的,那么它应该是什么呢?页面滚动===25
var pageScrolled = ... // gets percentage scrolled (ie: 80 or NaN if tracklength == 0)