Why Javascript Can't Get The Style Value But Can Change It?
I need to pass the tag data to the function and read it in that function , I tried to pass the tag via 'this' , i could change some style elements but i couldn't read the style dat
Solution 1:
The style
object on elements only has the style information applied specifically to the element, not information applied to it via stylesheets. So to start with, your tab.style.backgroundColor
will be blank, because there's no style="background-color: ..."
on the element.
To get the computed style of an element, you use the getComputedStyle
function (on anything modern) or the currentStyle
property (on old IE):
alert(getComputedStyle(tab).backgroundColor);
For old IE, a simple shim is easily added:
if (!window.getComputedStyle) {
window.getComputedStyle = function(element, pseudo) {
if (typeof pseudo !== "undefined") {
throw"The second argument to getComputedStyle can't be polyfilled";
}
return element.currentStyle;
};
}
Example:
if (!window.getComputedStyle) {
window.getComputedStyle = function(element, pseudo) {
if (typeof pseudo !== "undefined") {
throw"The second argument to getComputedStyle can't be polyfilled";
}
return element.currentStyle;
};
}
var div = document.querySelector(".foo");
snippet.log("Background color before changing: " +
getComputedStyle(div).backgroundColor);
setTimeout(function() {
div.style.backgroundColor = '#4ff';
snippet.log("Background color after changing: " +
getComputedStyle(div).backgroundColor);
}, 1000);
.foo {
background-color: #ff4;
}
<divclass="foo">My background is yellow to start with, because of the class <code>foo</code>, then code turns it cyan</div><!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --><scriptsrc="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Post a Comment for "Why Javascript Can't Get The Style Value But Can Change It?"