我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。


当前回答

HTML程序,用于显示通过将鼠标拖到元素上,您就复制了它并自己使用它<!DOCTYPE html><html><head><标题>元素的位置</title><!-- scropt获取位置--><script type=“text/javascript”>函数getPositionXY(元素){var rect=元素.getBoundingClientRect();document.getElementById('text').innerHTML='X:'+rect.X+'<br>'+'Y:'+direct.Y;}</script></head><body><p>将鼠标移到文本上</p><div onmouseover=“getPositionXY(this)”>职位:<p id=“text”></p></div></body></html>

其他回答

HTML程序,用于显示通过将鼠标拖到元素上,您就复制了它并自己使用它<!DOCTYPE html><html><head><标题>元素的位置</title><!-- scropt获取位置--><script type=“text/javascript”>函数getPositionXY(元素){var rect=元素.getBoundingClientRect();document.getElementById('text').innerHTML='X:'+rect.X+'<br>'+'Y:'+direct.Y;}</script></head><body><p>将鼠标移到文本上</p><div onmouseover=“getPositionXY(this)”>职位:<p id=“text”></p></div></body></html>

我成功地使用Andy E的解决方案,根据用户单击的表行中的链接来定位引导2模式。该页面是Tapestry 5页面,下面的javascript被导入到java页面类中。

javascript代码:

function setLinkPosition(clientId){
var bodyRect = document.body.getBoundingClientRect(),
elemRect = clientId.getBoundingClientRect(),
offset   = elemRect.top - bodyRect.top;
offset   = offset + 20;
$('#serviceLineModal').css("top", offset);

}

我的模式代码:

<div id="serviceLineModal" class="modal hide fade add-absolute-position" data-backdrop="static" 
 tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="top:50%;">
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
    <h3 id="myModalLabel">Modal header</h3>
</div>

<div class="modal-body">
    <t:zone t:id="modalZone" id="modalZone">
        <p>You selected service line number: ${serviceLineNumberSelected}</p>
    </t:zone>
</div>

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <!-- <button class="btn btn-primary">Save changes</button> -->
</div>

循环中的链接:

<t:loop source="servicesToDisplay" value="service" encoder="encoder">
<tr style="border-right: 1px solid black;">       
    <td style="white-space:nowrap;" class="add-padding-left-and-right no-border"> 
        <a t:type="eventLink" t:event="serviceLineNumberSelected" t:context="service.serviceLineNumber" 
            t:zone="pageZone" t:clientId="modalLink${service.serviceLineNumber}"
            onmouseover="setLinkPosition(this);">
            <i class="icon-chevron-down"></i> <!-- ${service.serviceLineNumber} -->
        </a>
    </td>

页面类中的java代码:

void onServiceLineNumberSelected(String number){
    checkForNullSession();
    serviceLineNumberSelected = number;
    addOpenServiceLineDialogCommand();
    ajaxResponseRenderer.addRender(modalZone);
}

protected void addOpenServiceLineDialogCommand() {
    ajaxResponseRenderer.addCallback(new JavaScriptCallback() {
        @Override
        public void run(JavaScriptSupport javascriptSupport) {
            javascriptSupport.addScript("$('#serviceLineModal').modal('show');");
        }
    });
}

希望这对某人有所帮助,这篇文章帮了大忙。

我可以像element.offsetLeft或element.ooffsetTop一样。示例:document.getElementById('profileImg').offsetLeft

更新:

递归方法(在我以前的答案中)创建了许多调用堆栈。在这种情况下,我们可以使用while循环来避免递归:

/**
 *
 * @param {HTMLElement} el
 * @return {{top: number, left: number}}
 */
function getDocumentOffsetPosition(el) {
    let top = 0, left = 0;
    while (el !== null) {
        top += el.offsetTop;
        left += el.offsetLeft;
        el = el.offsetParent;
    }
    return {top, left};
}

旧答案:

/**
 *
 * @param {HTMLElement} el
 * @return {{top: number, left: number}}
 */
function getDocumentOffsetPosition(el) {
    var position = {
        top: el.offsetTop,
        left: el.offsetLeft
    };
    if (el.offsetParent) {
        var parentPosition = getDocumentOffsetPosition(el.offsetParent);
        position.top += parentPosition.top;
        position.left += parentPosition.left;
    }
    return position;
}

感谢Thinkingtiff的回答,这只是另一个版本。

您可以将两个财产添加到Element.protype中,以获得任何元素的顶部/左侧。

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

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

这被称为:

var x = document.getElementById( 'myDiv' ).documentOffsetLeft;

下面是一个将结果与jQuery的offset().top和.left进行比较的演示:http://jsfiddle.net/ThinkingStiff/3G7EZ/