• 【javascript基础】之【确定元素坐标】


    【javascript基础】之【确定元素坐标】

      IE、FireFox3以及更高版本和Opera9.5以及更高版本都提供了getBoundingClientRect()方法,这个方法返回一个矩形对象,left、top、right、bottom,这些属性返回的是节点相对于浏览器(0,0)坐标(节点相对于视口的位置)的位置。但IE认为文档的左上角坐标是(2,2),而FireFox Opera则将传统的(0,0)作为起点坐标,因此开始的时候,检查一下位于(0,0)的位置。

     demo:

    <div id="msg" style="400px;height:400px;background:#0046a3;margin:40px;"></div>
    <script type="text/javascript">

    var m = document.getElementById("msg");

    function offset(elem){
        if(!elem){
            throw '不是一个有效的节点';
        }
        var scrollTop = document.documentElement.scrollTop,
            scrollLeft = document.documentElement.scrollLeft,
            returnValue = null;
        if(elem.getBoundingClientRect){   //支持getBoundingClientRect
            if(typeof arguments.callee.offset !== 'number'){
                var temp = document.createElement("div");
                temp.style.cssText = "position:absolute;top:0;left:0;";
                document.body.appendChild(temp);
                arguments.callee.offset = - temp.getBoundingClientRect().top - scrollTop;   //为了防止函数调用的时候,窗口被滚动了
                document.body.removeChild(temp);
                temp = null;
            }
            var rect = elem.getBoundingClientRect(),
                offset = arguments.callee.offset;
            returnValue = {
                left : rect.left + offset,
                right : rect.right + offset,
                top : rect.top + offset,
                bottom : rect.bottom + offset
            };
        }else{                         //不支持getBoundingClientRect
            var offsetParent = elem, 
                left = 0,
                top = 0;
            while( offsetParent != null ){
                left += offsetParent.offsetLeft;
                top += offsetParent.offsetTop;
                offsetParent = elem.offsetParent;
            }
            returnValue = {
                left : left - scrollLeft,
                right : left + elem.offsetWidth - offsetLeft,
                top : top - scrollTop,
                bottom : top + elem.offsetHeight - scrollTop
            };
        }
        
        return returnValue;
    }

    var t = offset(m);
    alert('top:' + t.top + '\n' + 'left:' + t.left + '\n' + 'right:' + t.right + '\n' + 'bottom:' + t.bottom);

    </script>

     参考:javascript高级程序设计第二版

  • 相关阅读:
    centos7安装Oracle12c
    Spring框架学习总结(上)
    如何教会女友递归算法?
    别翻了,这篇文章就是要让你入门java多线程!
    【从今天开始好好学数据结构04】程序员你心中就没点“树”吗?
    【从今天开始好好学数据结构03】链表
    【从今天开始好好学数据结构02】栈与队列
    别翻了,这篇文章绝对让你深刻理解java类的加载以及ClassLoader源码分析【JVM篇二】
    深入理解java继承从“我爸是李刚”讲起
    深入理解java多态没有烤山药的存在,java就不香了吗?
  • 原文地址:https://www.cnblogs.com/sniper007/p/2471632.html
Copyright © 2020-2023  润新知