简体   繁体   English

如何在JavaScript中进行css3转换后获取元素的位置?

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

I saw this posted in 2 different forms on stackoverflow, but the solutions don't work for me. 我在stackoverflow上看到了这两种不同的形式,但解决方案对我不起作用。

Essentially, I have an item that I will translate. 基本上,我有一个项目,我将翻译。 When I do a obj.style.left or obj.offsetLeft, after the element has been translated, I get 0. Is there anyway I can get the coordinates/position of an element after it has been translated with css3? 当我执行obj.style.left或obj.offsetLeft时,在元素被翻译之后,我得到0.无论如何,我可以在用css3翻译后得到元素的坐标/位置吗?

I can't use jQuery (because I can't and also because I want to understand the solution, not just use the library without understanding what is happening underneath) 我不能使用jQuery(因为我不能也因为我想了解解决方案,而不仅仅是使用库而不了解下面发生的事情)

Any ideas? 有任何想法吗?

Thanks much! 非常感谢!

You can use getBoundingClientRect() : 你可以使用getBoundingClientRect()

Imagine the following html block: 想象一下下面的html块:

<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: 现在您可以使用以下JavaScript来获取正确的位置:

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 : 你可以在jsfiddle中查看结果:

I tested on FF, IE and chrome, and it worked on all my tests. 我测试了FF,IE和chrome,它适用于我的所有测试。

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/ http://jsfiddle.net/duopixel/wzZ5R/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM