获取相对于视口顶部的元素位置 [英] Get an element position relative to the top of the viewport

查看:70
本文介绍了获取相对于视口顶部的元素位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取元素相对于视口顶部而不是整个文档的顶部位置.

I need to get the top position of an element relative to the top of the viewport, not the whole document.

我尝试了offset().top;返回相对于文档的顶部位置,而我尝试了scrollTop()总是返回0而不管元素在视口中的可见性.

I tried offset().top; which returns the top position relative to the document, and I tried scrollTop() which always returns 0 regardless of the element's visibility in the viewport.

推荐答案

您可以使用

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

工作示例

function get(){
  $('#output').html($('#element').offset().top - $(window).scrollTop());
}

get();
$(window).scroll(get);

#element {
  width:100px;
  height:100px;
  background:red;
}

#output {
  position:fixed;
  background:#000;
  color:#fff;
  width:100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="element"></div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />

这篇关于获取相对于视口顶部的元素位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆