简体   繁体   English

使用JavaScript计算li元素和视口之间的距离

[英]Calculate distance between li element and viewport using JavaScript

As shown in figure below... 如下图所示。

Black box is the screen size, the viewport. 黑框是屏幕尺寸,即视口。 The red dotted box is the size of the entire page, which has been scrolled out of the viewport. 红色虚线框是整个页面的大小,该页面已滚动到视口之外。 The green dotted boxes are li elements. 绿色的虚线框是li元素。 Now I want to calculate the distance between a specific li and the top edge of the viewport, represented by the red arrow. 现在,我要计算特定li和视口顶部边缘之间的距离,用红色箭头表示。

I'm okay with a jQuery solution. 我可以使用jQuery解决方案。

屏幕和视口刮擦

var distanceToTop = document.querySelector("#your-li").getBoundingClientRect().top

Quite easy with jQuery too : jQuery也很容易:

Demo 演示

$('#element').offset().top-$(window).scrollTop();

Best of both worlds : 两全其美 :

$('#element')[0].getBoundingClientRect().top;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM