客户端Javascript - 计算文档和元素的位置

【摘抄至:Javascript 权威指南 - 15 章 】


零、文档坐标和视口坐标

  要在两种坐标系之间相互切换,必须加上或减去滚动的偏移量。

一、getBoundingClientRect(),获取元素尺寸与位置的简单方法

  返回视口坐标(viewport),方法中的"Client"是一种间接指代,就是Web浏览器客户端定义的窗口或视口。

  left、top 表示元素的左上角X、Y坐标。

  right、bottom 表示元素的右下角X、Y坐标。

二、HTML元素:

  1、offsetWidth、offsetHeight 以CSS像素返回元素的尺寸,包含边框与内边距,除去了外边距。

  2、offsetLeft、offsetTop 返回元素的X、Y坐标。

    对于很多元素,这些值是文档坐标;

    对于已定位元素的后代元素和一些其他元素(如表格单元),这些值是相对于祖先元素的而非文档。

  3、offsetParent 指定这些属性所相对的父元素,如果offsetParent为null,这些属性都是文档坐标。

  4、用offsetLeft和offsetTop计算元素e的位置需要一个循环,

    通过循环offsetParent对象链来累加偏移量,计算指定元素的文档坐标。

  5、clientWidth、clientHeight 类似 offsetWidth、offsetHeight,不同的是不包括边框大小,只包含内容与内边距。

        clientLeft、clientTop 属性没什么用处,通常等于左边与上边的边框宽度。

    对于内联元素,以上4个属性总是为0。

  6、scrollWidth、scrollHeight 是元素的内容+内边距+任何溢出内容的尺寸。

    scrollLeft、scrollTop 指定元素的滚动条位置。

 

 

示例:【WdataPicker 日期选择控件,弹框显示位置的计算方法:】

        function B(I) {
            var G = I.position.left,
                B = I.position.top,
                C = I.el;
            if (C == S) return;
            if (C != I.srcEl && (O(C) == "none" || C.type == "hidden")) C = I.srcEl;
            var H = V(C),    // input 相对 iframe 的视窗位置 (相对不变)
                $ = F(X),    // iframe 相对 top 的视窗位置
                D = L(U),    // top window 尺寸宽高
                A = Z(U),    // top window 滚动条位置
                E = $dp.dd.offsetHeight,
                _ = $dp.dd.offsetWidth;
            if (isNaN(B)) B = 0;
            if (($.topM + H.bottom + E > D.height) && ($.topM + H.top - E > 0)){
                B += A.top + $.topM + H.top - E - 2;
            }else {
                // B += A.top + $.topM + Math.min(H.bottom, D.height - E) + 2;
                B += A.top + Math.min($.topM + H.bottom, D.height - E) + 2;
            }
            if (isNaN(G)) G = 0;
            G += A.left + Math.min($.leftM + H.left, D.width - _ - 5) - (R ? 2 : 0);
            I.dd.style.top = B + "px";
            I.dd.style.left = G + "px"
        }

 

  

posted @ 2018-12-07 11:02  chenyizh  阅读(185)  评论(0)    收藏  举报