How do I get the position of an element after css3 translation in JavaScript?

后端 未结 2 1788
走了就别回头了
走了就别回头了 2020-12-03 16:36

I saw this posted in 2 different forms on stackoverflow, but the solutions don\'t work for me.

Essentially, I have an item that I will translate. When I do a obj.st

相关标签:
2条回答
  • 2020-12-03 17:24

    Ok, hold tight because this is not nice:

    window.addEventListener('load', function(){
      var node = document.getElementById("yourid");
      var curTransform = new   WebKitCSSMatrix(window.getComputedStyle(node).webkitTransform);
      console.log(node.offsetLeft + curTransform.m41); //real offset left
      console.log(node.offsetTop + curTransform.m42); //real offset top
    });
    

    You can play with it here:

    http://jsfiddle.net/duopixel/wzZ5R/

    0 讨论(0)
  • 2020-12-03 17:30

    You can use getBoundingClientRect():

    Imagine the following html block:

    <div class="centralizer popup">
        <div class="dragger"></div>
    </div>
    

    And the style:

    body {
        background:#ccc;
    }
    .centralizer {
        position:absolute;
        top:150px;
        left:170px;
        width:352px;
        height:180px;
        overflow:auto;
        -webkit-transform: translateY(-50%) translateX(-50%);
        -moz-transform: translateY(-50%) translateX(-50%);
        -ms-transform: translateY(-50%) translateX(-50%);
        transform: translateY(-50%) translateX(-50%);
    }
    .popup {
        background:white;
        box-shadow:0 0 0 2px rgba(0, 0, 0, 0.1), 0 0 15px rgba(0, 0, 0, 0.3);
        border-radius:3px;
    }
    .dragger {
        background:#eee;
        height:35px;
        border-radius:3px 3px 0 0;
        border-bottom:1px solid #ccc;
    }
    

    Now you can use the following javascript to get the correct position:

    var popup = document.querySelector('.popup');
    var rect = popup.getBoundingClientRect();
    
    console.log("popup.getBoundingClientRect(): \n" + "x: " + rect.left + "\ny: " + rect.top);
    

    You can check the result in the jsfiddle:

    I tested on FF, IE and chrome, and it worked on all my tests.

    0 讨论(0)
提交回复
热议问题