当我点击视频播放时,尝试滚动具有大量数据的div。
我遇到了一个奇怪的问题,我的scrollTop为211.25
,但我的scrollHeight
为711
,clientHeight为500px
我必须在scrollTop上使用Math.floor
使其成为偶数。
这个.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);
});
}());
scrollTop >= scrollHeight - clientHeight
呢? - NickolayscrollTop >= scrollHeight - clientHeight
不总是有效,因为有时候比较结果可能会像100.75 >= 101
这样,由于 100.75 没有被进位到 101(而且在这个例子中 scrollTop 的值永远不会大于 100.75),所以检查失败。在我的测试中,Math.round(scrollTop) >= scrollHeight - clientHeight
在我遇到的情况下似乎总能奏效。我一直在想为什么人们设计 API 的方式会是这样... 哦,就让这个四舍五入吧,那个跳过吧。 - trusktr