JS获取控件绝对位置

来源:互联网 发布:审批系统 数据库设计 编辑:程序博客网 时间:2024/06/05 17:48


<!DOCTYPE html><html><head>    <title></title>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <script type="text/javascript">        // 输出控件位置        function printPoint(pElement){            alert("该按钮位置为:左"+getAbsoluteLeft(pElement.id)+"上"+getAbsoluteTop(pElement.id));        }        //获取控件左绝对位置        function getAbsoluteLeft(pElementId) {            o = document.getElementById(pElementId);            oLeft = o.offsetLeft;                        while(o.offsetParent!=null) {                 oParent = o.offsetParent;                    oLeft += oParent.offsetLeft;                 o = oParent;            }            return oLeft;        }        //获取控件上绝对位置        function getAbsoluteTop(pElementId) {            o = document.getElementById(pElementId);            oTop = o.offsetTop;            while(o.offsetParent!=null)            {                  oParent = o.offsetParent ;                oTop += oParent.offsetTop ; // 加父层级顶部位置                o = oParent ;            }            return oTop ;        }            </script></head><body><div style="text-align:center;margin:0 auto;border:1px solid #000;width:200px;height:200px"><br><input id="button1" type="button"  style="width:125px;height:25px;" value = "查看该按钮位置" onclick="printPoint(this)" ></button><br><br><br><input id="button2" type="button"  style="width:125px;height:25px;" value = "查看该按钮位置" onclick="printPoint(this)" ></button><br><br><br><input id="button3" type="button"  style="width:125px;height:25px;" value = "查看该按钮位置" onclick="printPoint(this)" ></button><br></div></body></html>


原创粉丝点击