Jump to content

Geting Css position properties.


Omirion

Recommended Posts

It depends on hos the position is defined and what you are really after. If you have specified the position using in-line CSS properties OR if you have defined the CSS property using javascript, then you can get the value using javascript. If, however, the property is defined in a stylesheet, then javascript cannot get the value. You could probably write some really complext code to get the class or ID from the element and then read the stylesheet to find the appropriate class, and finally parse the properties of the class to find the position. But, that would be a lot of work.

 

Also, if the position is not even defined in the style properties and you are just trying to get the position that can be done, but there are browser compatability issues to contend with. There are some freely available scripts that can do this if you do a littel searching.

 

Anyway, here is an example script that gives four different examples of how the left property is defined. The sample javascript function can obtain the left position for two, but not the other two.

 

<html>
<head>
<style>
#div3 { position: absolute; left:400px; }
</style>

<script>

function test(divID)
{
  var divObj = document.getElementById(divID);

  alert( divObj.style.left );

}

</script>
</head>

<body>
<div id="div1" style="">One - No position defined</div>
<div id="div2" style="position:absolute; left:150;">Two - Defined In Line</div>
<div id="div3">Three - Defined in style sheet</div>
<div id="div4" style="position:absolute;">Four - Defined via javascript</div>

<br /><br /><br />
<button onclick="test('div1');">One</button><br />
<button onclick="test('div2');">Two</button><br />
<button onclick="test('div3');">Three</button><br />
<button onclick="test('div4');">Three</button><br />

<script type="text/javascript">
  document.getElementById('div4').style.left = '600px';
</script>

</body>
</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.