Retrieve the position (X,Y) of an HTML element relative to the browser window

前端 未结 27 3709
闹比i
闹比i 2020-11-21 04:59

I want to know how to get the X and Y position of HTML elements such as img and div in JavaScript relative to the browser window.

27条回答
  •  执笔经年
    2020-11-21 05:47

    I successfully used Andy E's solution to position a bootstrap 2 modal depending on what link in a table row a user clicks on. The page is a Tapestry 5 page and javascript below is imported in the java page class.

    javascript:

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

    }

    My modal code:

    The link in the loop:

    
           
         
            
                 
            
        
    

    And the java code in the page class:

    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');");
            }
        });
    }
    

    Hope this helps someone, this post helped out.

提交回复
热议问题