当我按下视频播放时,试图向下滚动一个带有大量数据的div。
我发现了一个奇怪的问题,我的scrollTop是211.25,但scrollHeight是711,clientHeight是500px
我必须将Math.floor放在scrollTop上,才能使它达到偶数。
这个.25px是从哪里来的?
HTML:
<video id="v0" tabindex="0" autobuffer="autobuffer" preload="preload" controls>
<source src="http://res.cloudinary.com/david-wash-blog/video/upload/sample-video.mp4" type="video/mp4"></source>
<p>Sorry, your browser does not support the <video> element.</p>
</video>
<div id="data-scroll">
SOME DATA
SOME DATA
SOME DATA
SOME DATA
SOME DATA
SOME DATA
</div> CSS:
#v0 {
width: 100%;
height: 200px;
}
#data-scroll {
width: 500px;
height: 500px;
overflow-y: scroll;
border: solid red 10px;
}
#footer {
height: 400px;
}JAVASCRIPT:
(function(){
var vid = document.getElementById('v0');
var dataScroll = document.getElementById('data-scroll');
var controls = document.getElementById('controls');
function playScroll(){
console.log(`clientHeight:${dataScroll.clientHeight}`);
console.log(`scrollHeight: ${dataScroll.scrollHeight}`);
console.log(`scrolling dataScroll @ ${dataScroll.scrollTop}`);
script.scrollTop += 100;
if(dataScroll.scrollHeight - Math.floor(dataScroll.scrollTop) === script.clientHeight){
console.log(`stop scrolling dataScroll @ ${dataScroll.scrollTop}`);
window.cancelAnimationFrame(playScroll);
}
window.requestAnimationFrame(playScroll);
}
vid.addEventListener('play', function(){
window.requestAnimationFrame(playScroll);
});
}());发布于 2022-02-11 07:00:03
为什么scrollTop有小数部分?
因为网络规范的作者出于一些奇怪的随机原因而喜欢它,字面意思是。
很可能你要找的是:
// It reached the bottom.
Math.round(scrollTop) >= scrollHeight - clientHeight到目前为止一直在为我工作。我不知道还有什么更好的,但如果我发现了,我会更新的。
编辑:前一个版本并不总是有效的。有时,在舍入后,scrollTop会比scrollHeight - clientHeight稍多或更少,特别是在内容被缩放的情况下(f.e。缩放或CSS转换)。
这就是我现在使用的,工作得很好的,用Math.abs来处理或多或少的情况:
function isScrolledToBottom(el) {
// NOTE: scrollTop is fractional, while scrollHeight and clientHeight are
// not, so without this Math.abs() trick then sometimes the result won't
// work because scrollTop may not be exactly equal to el.scrollHeight -
// el.clientHeight when scrolled to the bottom.
return Math.abs(el.scrollHeight - el.clientHeight - el.scrollTop) < 1
}注意,我不使用window API,只使用元素API,因为这适用于每种滚动情况,包括页面的顶层滚动。
对于顶级卷轴,我们可以这样使用它:
isScrolledToBottom(document.documentElement)但是我们也可以使用它在页面中任何嵌套的元素中滚动。
https://stackoverflow.com/questions/56718739
复制相似问题