zoukankan      html  css  js  c++  java
  • js各浏览器兼容取的元素的位置X坐标 Y坐标

    JS code:

    function getElementPos(elementId)
    {
        var ua = navigator.userAgent.toLowerCase();
        var isOpera = (ua.indexOf('opera') != -1);
        var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof
        var el = document.getElementById(elementId);
        if(el.parentNode === null || el.style.display == 'none') 
        {
            return false;
        } 
    
    
        var parent = null;
        var pos = []; 
        var box;
    
        if(el.getBoundingClientRect) //IE
        { 
            box = el.getBoundingClientRect();
            var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
            var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
            return {x:box.left + scrollLeft, y:box.top + scrollTop};
        }
        else if(document.getBoxObjectFor) // gecko 
        {
            box = document.getBoxObjectFor(el); 
            var borderLeft = (el.style.borderLeftWidth)?parseInt(el.style.borderLeftWidth):0; 
            var borderTop = (el.style.borderTopWidth)?parseInt(el.style.borderTopWidth):0; 
            pos = ;
        }
        else // safari & opera 
        {
            pos = [el.offsetLeft, el.offsetTop]; 
            parent = el.offsetParent; 
    
            if (parent != el) 
            { 
                while (parent) 
                { 
                    pos[0] += parent.offsetLeft; 
                    pos[1] += parent.offsetTop; 
                    parent = parent.offsetParent;
                } 
            } 
    
            if (ua.indexOf('opera') != -1 || ( ua.indexOf('safari') != -1 && el.style.position == 'absolute' )) 
            { 
                pos[0] -= document.body.offsetLeft;
                pos[1] -= document.body.offsetTop; 
            } 
        } 
    
        if (el.parentNode) 
        { 
            parent = el.parentNode;
        } 
        else 
        {
            parent = null;
        }
    
        while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') 
        { 
            // account for any scrolled ancestors
            pos[0] -= parent.scrollLeft;
            pos[1] -= parent.scrollTop;
    
            if (parent.parentNode) 
            {
                parent = parent.parentNode;
            } 
            else 
            {
                parent = null;
            }
        } 
        return {x:pos[0], y:pos[1]};
    }
  • 相关阅读:
    git常用命令
    IDEA设置
    redis基础
    SQL 基础
    springboot 配置日志 打印不出来sql
    阿里巴巴开发规范最新版
    rabbitmq用户权限
    rabbitMQ配置文件
    RabbitMQ配置文件(rabbitmq.conf)
    C++模板编程:如何使非通用的模板函数实现声明和定义分离
  • 原文地址:https://www.cnblogs.com/guangxiaoluo/p/3337062.html
Copyright © 2011-2022 走看看