计算可滚动div内元素的顶部偏移量 [英] Calculate offset top of elements inside of a scrollable div
本文介绍了计算可滚动div内元素的顶部偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算可滚动div内的偏移顶部?我有两个要在内容div中滚动的div,我想将2个变量设置为true/false,这取决于它们在该内容div中的位置.
How can I calculate offset top inside a scrollable div? I have two divs that I want scroll inside my content div, and I want to set 2 variables to true/false, depending on where they are positioned inside that content div.
我尝试了类似的方法,但是我猜它可以计算出整个页面的偏移量,但实际上并没有用.我将滚动条绑定到该内容div,并想计算其位置:
I tried something like this but I guess it calculates the entire page offset, it doesn't really work. I bind scroll to that content div, and I want to calculate their positon:
angular.element(slideContent).bind("scroll", function () {
var contentScrollTop = angular.element(slideContent).scrollTop();
var slideOneOffset = slideOne.offset().top;
var slideTwoOffset = slideTwo.offset().top;
var firstSlideDistance = (contentScrollTop - slideOneOffset);
var secondSlideDistance = (contentScrollTop - slideTwoOffset);
});
推荐答案
我认为这应该可以帮助您实现大部分目标:
I think this should get you most of the way there:
// Position of first element relative to container top
var scrollTop = $(".container .element").offset().top - $(".container").offset().top;
// Position of selected element relative to container top
var targetTop = $(".container > *").offset().top - $(".container").offset().top;
// The offset of a scrollable container
var scrollOffset = scrollTop - targetTop;
// Scroll untill target element is at the top of its container
$(".container").scrollTop(scrollOffset);
————————————
———————————
编辑(2018年5月31日)
EDIT (May 31 2018)
我想这样更好:
var scrollOffset = $(".container .element")[0].offsetTop - $(".container")[0].offsetTop
这篇关于计算可滚动div内元素的顶部偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文