javascript 如何使用javascript获取左上角的x和y坐标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8847049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:45:52  来源:igfitidea点击:

how to get the top left x and y coordinate using javascript

javascriptjquery

提问by xonegirlz

I know that we can get width and height using clientWidth and clientHeight, however how do I figure out the top left x and top left y position of an element?

我知道我们可以使用 clientWidth 和 clientHeight 获取宽度和高度,但是如何计算元素的左上角 x 和左上角 y 位置?

回答by Sameera Thilakasiri

function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

Retrieve the position (X,Y) of an HTML element

检索 HTML 元素的位置 (X,Y)

Find X/Y of an HTML element with JavaScript

使用 JavaScript 查找 HTML 元素的 X/Y

These two links should be helpful.

这两个链接应该会有所帮助。

回答by WoLfulus

Using jQuery you can do this by calling .position() function. Like:

使用 jQuery,您可以通过调用 .position() 函数来完成此操作。喜欢:

$('#mydiv').position().left;
$('#mydiv').position().top;

This is the most reliable way, since it already calculates the position checking the CSS of elements and its parents.

这是最可靠的方法,因为它已经计算了检查元素及其父元素的 CSS 的位置。

You can see the full implementation here:

你可以在这里看到完整的实现:

http://code.jquery.com/jquery-1.7.1.jsat line 9077

http://code.jquery.com/jquery-1.7.1.js第 9077 行

回答by ThinkingStiff

To get the top you need to add the offsetTopof the element and the element's offsetParent's offsetTop. Do this all the way up the DOM to the document. That accounts for absolute, relative and fixed positioning. To get the left, do the same thing with offsetLeft.

为了让您需要添加顶部offsetTop的元素和元素offsetParentoffsetTop。从 DOM 到document. 这说明了绝对、相对和固定定位。要获得左侧,请使用offsetLeft.

These two functions add two properties to Element, documentOffsetTopand documentOffsetLeft, that will get top/left of any element:

这两个函数将两个属性添加到Element,documentOffsetTopdocumentOffsetLeft,这将获得任何元素的顶部/左侧:

window.Object.defineProperty( Element.prototype, 'documentOffsetTop', {
    get: function () { 
        return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
    }
} );

window.Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
    get: function () { 
        return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
    }
} );

This demo shows several combinations of element layout, comparing documentOffsetTopwith jQuery's offset().top.

这个演示展示了元素布局的几种组合,documentOffsetTop与 jQuery 的offset().top.

Demo: http://jsfiddle.net/ThinkingStiff/3G7EZ/

演示:http: //jsfiddle.net/ThinkingStiff/3G7EZ/

Script:

脚本:

window.Object.defineProperty( Element.prototype, 'documentOffsetTop', {
    get: function () { 
        return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
    }
} );

var line = document.getElementsByClassName( 'grid-line' )[0],
    grid = document.getElementById( 'grid' );

for( var index = 2; index < 100; index++ ) {
    var copy = line.cloneNode();
    copy.textContent = ( index * 10 );
    grid.appendChild( copy );
};

var offset = document.getElementById( 'absolute' );
offset.textContent = 'absolute: ' 
    + offset.documentOffsetTop + ', $' 
    + $( offset ).offset().top;

offset = document.getElementById( 'static' );
offset.textContent = 'static: ' 
    + offset.documentOffsetTop + ', $' 
    + $( offset ).offset().top;

offset = document.getElementById( 'static2' );
offset.textContent = 'static: ' 
    + offset.documentOffsetTop + ', $' 
    + $( offset ).offset().top;

offset = document.getElementById( 'relative' );
offset.textContent = 'relative: ' 
    + offset.documentOffsetTop + ', $' 
    + $( offset ).offset().top;

offset = document.getElementById( 'fixed-side' );
offset.textContent = 'fixed/absolute (side): ' 
    + offset.documentOffsetTop + ', $' 
    + $( offset ).offset().top;

offset = document.getElementById( 'fixed-top' );
offset.textContent = 'fixed/absolute (top): ' 
    + offset.documentOffsetTop + ', $' 
    + $( offset ).offset().top;

offset = document.getElementById( 'fixed-bottom' );
offset.textContent = 'fixed/absolute (bottom): ' 
    + offset.documentOffsetTop + ', $' 
    + $( offset ).offset().top;

offset = document.querySelectorAll( '#relative-wrapped-absolute div' )[0];
offset.textContent = 'absolute/relative/static (absolute/relative wrapped): ' 
    + offset.documentOffsetTop + ', $' 
    + $( offset ).offset().top;

offset = document.querySelectorAll( '#static-wrapped-static div' )[0];
offset.textContent = 'static (static wrapped): ' 
    + offset.documentOffsetTop  + ', $' 
    + $( offset ).offset().top;

HTML:

HTML:

<div id="static" class="offset">0</div>
<div id="static2" class="offset">0</div>
<div id="static-wrapped-static"><br /><div class="offset">0</div></div>
<div id="absolute" class="offset">0</div>
<div id="relative" class="offset">0</div>
<div id="fixed-side" class="offset">0</div>
<div id="fixed-top" class="offset">0</div>
<div id="fixed-bottom" class="offset">0</div>
<div style="position: relative;"><div id="relative-wrapped-absolute"><div class="offset">0</div></div></div>

<div id="grid"><div class="grid-line">10</div></div>

CSS:

CSS:

body {padding-left: 12px;}

#absolute {
    top: 100px;
    position: absolute;
}

#relative {
    top: 150px;
    position: relative;
}

#fixed-side {
    right: 0;
    position: fixed;
}

#fixed-top {
    left: 50%;
    position: fixed;
    top: 0;
}

#fixed-bottom {
    left: 50%;
    position: fixed;
    bottom: 0;
}

#relative-wrapped-absolute {
    top: 8px;
    position: relative;
}

#relative-wrapped-absolute div {
    position: absolute;
    top: 20px;
}

.offset {
    border: 1px solid black;
}

#grid {
    height: 100%;
    left: 0;
    position: absolute;
    top: 1px;
    width: 100%;
    z-index: -1;
}

.grid-line {
    border-bottom: 1px solid lightgray;
    font-size: 8px;
    height: 9px;
    line-height: 20px;
}

Output:

输出:

enter image description here

在此处输入图片说明

回答by Captain0

Do you need the x and y for a specific element.

您是否需要特定元素的 x 和 y。

$("#bnElement").offset().left;
$("#bnElement").offset().top;

Just have a look at the following post jQuery x y document coordinates of DOM objectregards

只要看看下面的帖子DOM对象jQuery的XY坐标文件问候

回答by Yash

Using querySelectorAll() method

使用querySelectorAll() 方法

    var domTree = [];
var allelems = document.querySelectorAll(tagsCheck ); // for all tags use --> '*'

for(var i = 0; i < allTags.length; i++){
    console.log(i+'  '+'Tag : '+ allTags[i].nodeName+'#'+allTags[i].id);  // getPath(allTags[i]);

    getPosition(allTags[i]);
    console.log('Coordinates  : {top   : '+allTags[i].getBoundingClientRect().top+', left   : '+allTags[i].getBoundingClientRect().left+' } ');

    console.log('Dimensions offset       :  {width : '+allTags[i].offsetWidth+', height : '+allTags[i].offsetHeight+' } ');
    console.log('Dimensions style  Q     :  {width : '+allTags[i].style.width+', height : '+allTags[i].style.height+' } '); 

    var singleTag = [];
    var jsonData = getTagInfo(allelems[i]); //singleTag.push(getFullXPath(allelems[i]));
    singleTag.push(jsonData);
    domTree.push(singleTag);
console.log(singleTag);

}
function getTagInfo(element){ 
    return '{ \"Xpath\": \"'+ getFullXPath(element) + '\", \"left\": '+element.getBoundingClientRect().left+',\"top\":  '+element.getBoundingClientRect().top+
    ',\"width\": '+element.offsetWidth+',\"height\" : '+element.offsetHeight+'}';
}

Using getElementsByTagName() and getComputedStyle()

使用getElementsByTagName() 和getComputedStyle()

function getElementDimensions(tagsCheck){
    var allElem = document.getElementsByTagName('*'); 
    for(i = 0, j = 0; i < allElem.length; i++) { 
        var elemstyle= window.getComputedStyle(allElem[i], null);
        if( tagsCheck.indexOf( allElem[i].tagName ) > -1 ){
            console.log(i+'  '+'Tag : '+allElem[i].tagName+'[@id : '+allElem[i].id);
            console.log('Dimensions style  E     :  {width : '+elemstyle.width+', height : '+elemstyle.height+' } '); 
        }
    }
}

positionand XPathof an HTML element

HTML 元素的位置XPath

function getPosition(element){ 
    var xPosition = 0; 
    var yPosition = 0; 
        while(element) { 
            xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
            yPosition += (element.offsetTop - element.scrollTop + element.clientTop); 
        element = element.offsetParent; 
        }
    console.log('GetPosition  : {top   : '+yPosition+', left   : '+xPosition+' } ');
}

回答by guy mograbi

I really liked jquery.simulateimplementation

我真的很喜欢jquery.simulate实现

function findCorner(elem) {
    var offset,
        document = $(elem.ownerDocument);
    elem = $(elem);
    offset = elem.offset();

    return {
        x: offset.left - document.scrollLeft(),
        y: offset.top - document.scrollTop()
    };
}

seems to capture a lot of scenarios. it brings you the position relative to screen.. so if I scrolled, some items may be in negative position. which is useful for automated tests that use drag & drop.

似乎捕捉到了很多场景。它为您提供相对于屏幕的位置.. 所以如果我滚动,某些项目可能处于负位置。这对于使用拖放的自动化测试很有用。

You can easily wrap it with jquery for cool syntax like so

你可以很容易地用 jquery 包装它以获得像这样的酷语法

$.fn.findCorner = function(){
    if ( this.length > 1 ) {
        return this.map(function(){ return findCorner(this); })
    } else {
        return findCorner(this[0]);
    }
};

and so do $('div').findCorner()..

也是$('div').findCorner()。。

回答by bZezzz

Maybe this can help you. ?!

也许这可以帮助你。?!

HTML

HTML

    <div>
    <p>Hello</p>
    </div>
    <p></p>

CSS

CSS

div { padding: 50px;}
p { margin-left:10px; }

JS

JS

    var p = $("p:first");
    var position = p.position();
    $("p:last").text( "left: " + position.left + ", top: " + position.top );

Demo: http://jsfiddle.net/bZezzz/TvMMv/

演示:http: //jsfiddle.net/bZezzz/TvMMv/