如何使用jquery / javascript获得精确的div定位

时间:2014-12-31 01:34:39

标签: javascript jquery html css

我正在尝试计算div定位。这是我的代码。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<style>
.content {width: 60%;
 position: relative;
  text-align: center ; 
    top: 150px;    
    left:300px;
    right:450px; border-style: solid;
    border-width: 5px;
}

</style>
</head>

<body>
<div class="content">
Testings content
</div>


<script>
    function ReadDivPos() {
            var content = document.getElementsByClassName('content');

            for (i = 0; i < content.length; i++) {
                console.log("Top " + content[i].getBoundingClientRect().top) //top
                console.log("left " + content[i].getBoundingClientRect().left) //left
                console.log("right " + content[i].getBoundingClientRect().right) //right
                console.log("offsetWidth " + content[i].offsetWidth); //width
            }
            var _divPos = "LEft "+content[0].getBoundingClientRect().left + ",Width " + content[0].offsetWidth + ",Avail Width " + window.screen.availWidth + ",Right " + content[0].getBoundingClientRect().right;
            return _divPos;
        }
        console.log(ReadDivPos());

</script>

</body>
</html>

当页面没有调整大小但是当页面调整大小并且屏幕上出现水平滚动条然后它不能正常工作时,此代码可以正常工作。如果页面调整大小,我如何获得div的确切位置。例如,这些是我用来解释问题的图像。

当页面调整大小并且滚动条位于最右侧时,div的左侧定位显示208px,这是错误的,应该是311像素。 When scroll bar is on the extreme right

当我移动左侧的滚动条然后我使用Chrome MeasureIT添加计算宽度然后它说311px。

enter image description here When scroll bar is on the extreme left

我想获得div的确切位置。我正在使用div的类来获取定位,因为我没有使用div id而且我只需要使用该类,所以这就是我如何做到但是它页面调整大小时不起作用。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

由于您已经在页面中加载了jQuery,请查看jQuery offset()position()方法并利用jQuery选择器。

<script>
    function ReadDivPos(selector) {
        var _divPos = "";

        $(selector).each(function() {
            var p = $(this).offset();
            var w = $(this).width();
            console.log("Top " + p.top) //top
            console.log("left " + p.left) //left
            console.log("right " + p.left + w) //right
            console.log("offsetWidth " + w); //width

            _divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
        });
        return _divPos;
    }

    console.log(ReadDivPos(".content"));
</script>