Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

css - 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.

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?

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)

Any ideas?

Thanks much!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(): 
" + "x: " + rect.left + "
y: " + rect.top);

You can check the result in the jsfiddle:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...