我需要找到元素和浏览器窗口底部之间的距离 [英] I need to find the distance between the element and the bottom of the browser window
问题描述
我需要找到元素与浏览器窗口底部之间的距离.
I need to find the distance between the element and the bottom of the browser window.
当我选择元素并且元素与浏览器窗口底部之间的距离小于50px时,我想使窗口自动滚动.
When I select the element, and the distance between the element and the bottom of the browser window is smaller than 50px, I want to make the window scroll automatically.
有什么想法吗?我更喜欢使用jQuery.
Any ideas? I'd prefer to use jQuery.
推荐答案
不同于其他系统,浏览器中的坐标是从上到下,这意味着浏览器的顶部是y = 0.
Unlike other systems coordinates in browser is from top to bottom, it means top of the browser is y=0.
有两个DOM元素属性,用于获取元素在页面上的位置.这些属性是element.offsetTop
和element.offsetHeight
There is two DOM element property for getting position of an element on the page. The properties are element.offsetTop
and element.offsetHeight
您可以通过计算element.offsetTop
和window.innerHeight
来计算元素和页面底部之间的间隔.
You can calculate the space between your element and bottom of the page by calculating element.offsetTop
and window.innerHeight
.
var space = window.innerHeight - element.offsetTop
如果要计算元素底部和窗口底部之间的空间,则还需要添加元素高度.
if you want to calculate space between bottom of your element and bottom of the window then you need to add your element height too.
var space = window.innerHeight - element.offsetTop + element.offsetHeight
有时需要进行此计算.认为您具有基于百分比的定位,并且您想通过像素知道元素的位置以执行某项操作.例如,您的div定位如下:
This calculation is sometimes necessary. Think you have percent based positioning and you want to know position of your element by pixels to do something. For example you have a div positioned like this:
div{
width:300px;
height:16.2%;
position:absolute;
top: 48.11%;
border:3px dotted black;
}
然后您想知道div何时靠近浏览器窗口以更改其颜色:
Then you want to know when the div is close to browser window to change it's color:
var div = document.querySelector('div'),
space = innerHeight - div.offsetTop + div.offsetHeight;
window.onresize = function(){
space = innerHeight - div.offsetTop + div.offsetHeight;
if(space < 200){
div.style.background = 'blue';
}
};
这篇关于我需要找到元素和浏览器窗口底部之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!