我已经为一个 div 实现了一个 onscroll 函数,它是这样工作的:
window.onscroll = function () {
document.getElementById("faceExtractor").style.top = (($(window).scrollTop()) + 50) + "px";
};
效果很好。现在我使 div 元素也可以拖动,这意味着在有人拖动 div a 但向下然后滚动后,由于 onscroll 函数,div 再次被放置在页面顶部下方 50px 处。我想解决这个问题,这样即使有人将它拖动到特定位置,div 也能在滚动时保持它的位置,我试过这个:
window.onscroll = function () {
topDistance = document.getElementById("faceExtractor").getBoundingClientRect().top;
if (topDistance < 50){
document.getElementById("faceExtractor").style.top = (($(window).scrollTop()) + 50) + "px";
} else {
var gap = ($(window).scrollTop()) + topDistance;
document.getElementById("faceExtractor").style.top = gap + "px";
}
};
但是滚动根本不起作用。我如何修改我的 onscroll 以便 div 保持它的位置而不总是放在页面顶部或静态位置?
最佳答案
window.onscroll = function () {
positionFromTop = document.getElementById("faceExtractor").offsetTop;
topDistance = document.body.parentElement.scrollTop+positionFromTop;
if (topDistance < 50){
document.getElementById("faceExtractor").style.top = topDistance+ "px";
} else {
var gap = topDistance;
document.getElementById("faceExtractor").style.top = gap + "px";
}
};
试试这个方法。并且,为“faceExtractor”Div 提供“position:absolute”。
关于javascript - div 的 onscroll 函数不适用于 getBoundingClientRect() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50596792/