zoukankan      html  css  js  c++  java
  • 【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高级程序设计第二版

  • 相关阅读:
    android截屏
    生产者消费者 ProducerConsumer
    实现RunOnUiThread和RunOnUiThreadBlock
    快速断网恢复方法
    JFrame2
    JFrame
    圆角矩形shader
    [转]Apache commons 工具包应用
    转载 [Java]读取文件方法大全
    转:aop的学习
  • 原文地址:https://www.cnblogs.com/sniper007/p/2471632.html
Copyright © 2011-2022 走看看