最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting the element position - { absolute|relative|fixed } returning null value? - Stack Overflow

programmeradmin2浏览0评论

Using javascript - we can set the element relative position such as

object.style.position="absolute"||"fixed"||"relative"

But,on using the same console.log(object.style.position) - it does not return the position applied on the object - it returns NULL. Am i missing something here or is there another way to achieve what i'm trying to achieve??

Using javascript - we can set the element relative position such as

object.style.position="absolute"||"fixed"||"relative"

But,on using the same console.log(object.style.position) - it does not return the position applied on the object - it returns NULL. Am i missing something here or is there another way to achieve what i'm trying to achieve??

Share Improve this question asked Jun 6, 2012 at 20:04 Vivek ChandraVivek Chandra 4,3569 gold badges35 silver badges39 bronze badges 6
  • It's working : jsfiddle/9TpfT – Alexandre Khoury Commented Jun 6, 2012 at 20:08
  • @mageek - not working(what i actually want) version - Fiddle – Vivek Chandra Commented Jun 6, 2012 at 20:14
  • It'll return null only if it hasn't been explicitly set. If it has been set then it will return the value. – Uncle Iroh Commented Jun 6, 2012 at 20:15
  • Yes, because I don't know why, but you can't get the style of an object if this css isn't inline (but you can set it). See my other answer here : stackoverflow./questions/10919859/… – Alexandre Khoury Commented Jun 6, 2012 at 20:16
  • @uncle that's the problem - how to retrieve it(if it was specified in CSS) was my question.. :) – Vivek Chandra Commented Jun 6, 2012 at 20:18
 |  Show 1 more ment

2 Answers 2

Reset to default 6

.style represents what's set on the element itself, much like the style attribute.

You could instead use getComputedStyle: http://jsfiddle/qAbTz/1/.

var div = document.getElementById("div");

console.log(div.style.position);              // "" (not null by the way)
console.log(getComputedStyle(div).position);​  // "fixed"

Note also (by the same logic presented by pimvdb), if you specify an initial position as part of the object's style, it is accessible by div.style.position.

<div id="div" style="position: absolute;"></div>

http://jsfiddle/qAbTz/4/

发布评论

评论列表(0)

  1. 暂无评论