Reputation: 5204
I'm trying to work out how, after changing style properties with javascript, I can revert to the value in the stylesheet (including the units).
In the example below, I'd like the output to read 100px
(the value in the CSS), rather than 10px
, as getComputedStyle
gives.
I'd also keep the dummy div at top:25px
, so removing the style
property won't work.
The best I have is cloning the node and reading the height and storing in a property (http://jsfiddle.net/daneastwell/zHMvh/4/), but this is not really getting the browser's default css value (especially if this is set in em
s).
http://jsfiddle.net/daneastwell/zHMvh/1/
<style>
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
</style>
<div id="elem-container">dummy</div>
<div id="output"></div>
<script>
function getTheStyle(){
var elem = document.getElementById("elem-container");
elem.style.left = "10px";
elem.style.top = "25px";
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("left");
document.getElementById("output").innerHTML = theCSSprop;
}
getTheStyle();
</script>
Upvotes: 29
Views: 22958
Reputation: 4362
The style object has a built-in removeProperty()
method, so you could do something like:
elem.style.removeProperty('left');
As far as I know, this will have exactly the same effect as setting the property to null
, as abaelter suggested. I just thought it might be worth including for the sake of completeness.
Upvotes: 8
Reputation: 153
Combining abaelter's answer and http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ gives us the below function:
var getCssStyle = function(elementId, cssProperty) {
var elem = document.getElementById(elementId);
var inlineCssValue = elem.style[cssProperty];
// If the inline style exists remove it, so we have access to the original CSS
if (inlineCssValue !== "") {
elem.style[cssProperty] = null;
}
var cssValue = "";
// For most browsers
if (document.defaultView && document.defaultView.getComputedStyle) {
cssValue = document.defaultView.getComputedStyle(elem, "").getPropertyValue(cssProperty);
}
// For IE except 5
else if (elem.currentStyle){
cssProperty = cssProperty.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
cssValue = elem.currentStyle[cssProperty];
}
// Put the inline style back if it had one originally
if (inlineCssValue !== "") {
elem.style[cssProperty] = inlineCssValue;
}
return cssValue;
}
Placing in your example code and testing:
console.log("getCssStyle: " + getCssStyle("elem-container", "left"));
Gives us getCssStyle: 100px
allowing you to see the original CSS value. If you just want to revert the value then do as abaelter says and null
the CSS value you want to revert.
Upvotes: 2
Reputation: 917
Just clear the inline style you wish to fallback to original stylesheet on.
elem.style.left = null;
Upvotes: 34