現在のプロパティを変更しようとしているだけだと仮定すると (単純に設定を解除しても)、問題が発生します。問題は、空の文字列が CSS プロパティの正当な値と見なされず、style
属性に追加されないことです。
auto
Chromium ではこれを回避できますが、キーワードを使用するだけであっても、プロパティの新しい値を明示的に宣言するだけです。それを念頭に置いて、1つのアプローチは以下のとおりです。
var propStates = {
// define the states, I'm only using two for a 'toggle'
// approach, adjust to taste.
'overflow': ['hidden', 'auto'],
'display': ['block', 'auto']
}
function removeCSSProperty(el, prop) {
if (!el || !prop) {
return false;
}
else {
// el can be either a node-reference *or* a string containing
// the id of the element to adjust
el = el.nodeType == 1 ? el : document.getElementById(el);
var current = window.getComputedStyle(el, null)[prop];
el.style[prop] = propStates[prop][0] == current ? propStates[prop][1] : propStates[prop][0];
}
}
document.getElementById('adjust').onclick = function() {
removeCSSProperty('test', 'overflow');
};
JS フィドルのデモ。
このアプローチでは、ブラウザーがwindow.getComputedStyle()
関数を理解する必要があります。IE <9 はサポートされていません (実際にはほとんどcurrentStyle
同じように見えますが)。