Forum Moderators: open

Message Too Old, No Replies

Absolute position from within a table

Computedstyle doesn't work as I expected

         

adni18

7:23 pm on May 25, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have a table with an element (say, an image) inside one of the cells. What I want to do is align another image (which is outside of the table and positioned absolutely) so that it has the same top-left corner. To do that, I thought I'd try:

obj1.style.top=document.defaultView.getComputedStyle(target1, null).top +"px";
obj1.style.left=document.defaultView.getComputedStyle(target1, null).left+"px";

but that didn't quite do the trick. I've also tried offsetTop and offsetLeft, but those seem to be somehow relative to the parents and such and I don't want to do (nor can I figure out) recursion for that. Any ideas?

daveVk

5:43 am on May 26, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



[webmasterworld.com...]

Code given there should do the trick.

subexpression

10:01 pm on May 29, 2010 (gmt 0)

10+ Year Member



andi18,

Try this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript">
var test = new function(){
var self = this;
self.imageposition = {
'image1': '',
'image2': '',
'load': function(img1,img2){
this.image1 = document.getElementById(img1);
this.image2 = document.getElementById(img2);
this.setposition(this.getposition(image2));
},
'getposition': function(el){
var curleft = curtop = 0;
if (el.offsetParent){
do {
curleft += el.offsetLeft;
curtop += el.offsetTop;
} while (el = el.offsetParent);
return [curleft,curtop];
}
},
'setposition': function(pos){
this.image1.style.top = pos[0] + 'px';
this.image1.style.left = pos[1] + 'px';
}
};
};
window.onload = function(){
test.imageposition.load('image1','image2');
}
</script>
</head>
<body>
<img src="images/image1.gif" id="image1" style="position:absolute;top:0px;left:0px;" />
<table>
<tr>
<td><img src="images/image2.gif" id="image2" /></td>
</tr>
</table>
</body>
</html>