我有一个网页,当它向下滚动时,文本在到达文本的最后一段时会冻结,但是图像会继续滚动。我已经实现了工作,但是当我点击并拖动滚动条时,用鼠标滚轮滚动时会有很多麻烦。
我是否可以对这段代码进行任何优化以使工作按预期进行,或者是否有不同的方式来完成相同的任务?
window.addEventListener('scroll', function (e) {
window.requestAnimationFrame(keepTextStationary);
//keepTextStationary(); // Less janky, but still horrible
});
function keepTextStationary() {
var textRect = writtenContent.getBoundingClientRect();
var imageRec = images.getBoundingClientRect();
if (textRect.bottom < window.innerHeight && document.documentElement.scrollTop > 0) {
writtenContent.style.position = 'relative';
writtenContent.style.bottom = (225 - document.documentElement.scrollTop) + 'px';
if (imagesTop === undefined) {
imagesTop = imageRec.y;
}
} else {
writtenContent.style.bottom = (225 - document.documentElement.scrollTop) + 'px';
}
if (imageRec.y >= imagesTop) {
writtenContent.style.position = '';
}
}这是网站,你可以看到问题。https://bowerbankninow.azurewebsites.net/exhibitions/oscar-perry-the-pheasant
发布于 2018-10-19 09:09:41
每次调用getBoundingClientRect时,都会导致布局崩溃。尝试删除滚动事件:
var lastScrollY = 0;
var ticking = false;
function keepTextStationary() {
var textRect = writtenContent.getBoundingClientRect();
var imageRec = images.getBoundingClientRect();
if (textRect.bottom < window.innerHeight && lastScrollY > 0) {
writtenContent.style.position = 'relative';
writtenContent.style.bottom = (225 - lastScrollY) + 'px';
if (imagesTop === undefined) {
imagesTop = imageRec.y;
}
} else {
writtenContent.style.bottom = (225 - lastScrollY) + 'px';
}
if (imageRec.y >= imagesTop) {
writtenContent.style.position = '';
}
ticking = false;
}
function onScroll() {
lastScrollY = document.documentElement.scrollTop;
requestTick();
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(keepTextStationary);
ticking = true;
}
}
window.addEventListener('scroll', onScroll );有关深入说明,请参阅本文:https://www.html5rocks.com/en/tutorials/speed/animations/
发布于 2018-10-19 07:33:57
你不知道。
javascript中的重新定位/样式设置是在CSS加载之后进行的。糟糕的练习。你能做的就是让它看起来不那么恐怖。
为什么纯CSS不是一个选项?
https://stackoverflow.com/questions/52884798
复制相似问题