Next in this lesson: ClassName Swap
An element's style attribute can be read just like any other attribute, except that you use camel-cased property names.
For examle, el.currentStyle["margin-bottom"]
will never return a value, though el.currentStyle["marginBottom"]
usually will. Essentially, you just replace the hyphen with nothing
and then capitalize the next letter.
var visibility = obj.style.visibility;
In practice, reading style values is not so simple.
The rendered style of an element is computed internally by the
browser. Reading the style attribute of an element will reveal
the element's attribute value.
Reading an element's style attribute will
not reveal the value that is determined by the style sheet(s)
or values that are inherited (e.g. line-height).
The function below tries to read the property from the
defaultView
(see
w3c).
Failing that, it looks to the object's currentStyle property (see
IE).
In a visual browser, defaultView is the visual representation
of the element's computed style after all override css has been handled
and inherited values have been calculated by the browser.
currentStyle does not return a visual representation. With
currentStyle, you will often get values such as "100%" or "auto."
Such values do not help calculate the dimensions of an element.
Explorer requires camel-cased property names for currentStyle,
just like when reading inline styles.
function getStyle(el, style) { if(!document.getElementById) return; var value = el.style[toCamelCase(style)]; if(!value) if(document.defaultView) value = document.defaultView. getComputedStyle(el, "").getPropertyValue(style); else if(el.currentStyle) value = el.currentStyle[toCamelCase(style)]; return value; } /** toCamelCase(input) * Converts string input to a camel cased version of itself. * For example: * toCamelCase("z-index"); // returns zIndex * toCamelCase("border-bottom-style"); // returns borderBottomStyle. */ function toCamelCase(s) { for(var exp = toCamelCase.exp; exp.test(s); s = s.replace(exp, RegExp.$1.toUpperCase()) ); return s; } toCamelCase.exp = /-([a-z])/;
Since currentStyle can return non-pixel values such as "auto",
consider using 4 of IE's special properties:
el.pixelTop,
el.pixelLeft,
el.pixelWidth,
el.pixelHeight.
These read-only properties return a number, which may increase the performance of your
application if you're using parseInt.
CSS rules that are not part of an elements style
attribute can only be read by obj.style[style]
after they have been set with JavaScript.
In NS, an element's style's value is not always the same as what you set its
style value to. This happens with backgroundImage values,
which are converted to full URLs, and with color values, which are converted to rgb.