在javascript中获取div位置(顶部)? [英] Get div position (top) in javascript?

查看:156
本文介绍了在javascript中获取div位置(顶部)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个div使用 top:-26px; 设置CSS的高度。我有其他divs我想与该div对齐的其他地方。我注意到在jQuery写作 .css('top')让我的CSS而不是div的y坐标。我如何获得使用javascript的绝对x,y位置?

解决方案

我会给你香草解决方案..不要抱怨..添加一个[0]到你的元素,它是固定的! :P希望这有助于。

 函数getOffset(el){
var _x = 0;
var _y = 0; (el&!isNaN(el.offsetLeft)&&!isNaN(el.offsetTop)){
_x + = el.offsetLeft - el.scrollLeft;

_y + = el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return {top:_y,left:_x};
}
var x = getOffset(document.getElementById('yourElId')).left;


One div i set the height in css using top:-26px;. I have other divs other places where i'd like to align with that div. I notice in jquery writing .css('top') gets me my css and not the y coord of the div. How do i get the absolute x,y position using javascript?

解决方案

I will give you the vanilla solution.. don't complain.. add a [0] to your element and it's fixed! :P hope this helps.

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('yourElId') ).left; 

这篇关于在javascript中获取div位置(顶部)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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