JS: получение стилей из CSS
Получить значения CSS стилей элемента можно с помощью метода getComputedStyle или currentStyle для IE. А как объединить эти два метода в кроссбраузерную функцию? Вот что я нашел:
if (!window.getComputedStyle) {
window.getComputedStyle = function(el, pseudo) {
this.el = el;
this.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
}
return this;
}
}
window.onload = function() {
var cs = window.getComputedStyle(document.getElementById('linkId'), "");
var out = "";
out += "color:" + cs.getPropertyValue("color") + "\n";
out += "float:" + cs.getPropertyValue("float") + "\n";
out += "background-color:" + cs.getPropertyValue("background-color");
alert(out);
}
if (typeof document.defaultView == 'undefined')
document.defaultView = {};
if (typeof document.defaultView.getComputedStyle == 'undefined')
{
document.defaultView.getComputedStyle = function(element, pseudoElement)
{
return element.currentStyle;
}
}
function getStyle(el, cssprop){
if (el.currentStyle) //IE
return el.currentStyle[cssprop]
else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
return document.defaultView.getComputedStyle(el, "")[cssprop]
else //try and get inline style
return el.style[cssprop]
}На webew.ru написано: "currentStyle в IE принимает ключи, записанные верблюжим шрифтом, поэтому необходимо преобразование вида border-color -> borderColor". Получается getComputedStyle работает с обычными CSS ключами? Метод getComputedStyle работет только с CamelCase, а вот getPropertyValue, использованный в примере на webew.ru,принимает обычные CSS ключи, сравните:
<div id="test">This is some text</div>
<script type="text/javascript">
var mydiv=document.getElementById("test")
alert("getComputedStyle & backgroundColor: "+
document.defaultView.getComputedStyle(mydiv, "")['backgroundColor']);
alert("getPropertyValue & background-color: "+
document.defaultView.getComputedStyle(mydiv, '').getPropertyValue("background-color"));
</script>
Еще и с float`ом у Эксплорера заморочки. Все нормальные браузеры получают значение float по ключу cssFloat, а IE требует styleFloat. Opera 10 тоже обрадовала :), в ней работает и getComputedStyle и currentStyle, а для получения float`a ей в любом случае нужно указывать cssFloat.
Вот, что у меня в конечном итоге получилось:
function getStyle(el, cssprop){
if (document.defaultView && document.defaultView.getComputedStyle)
{//Normal
if (cssprop == 'float') cssprop = 'cssFloat';
return document.defaultView.getComputedStyle(el, '')[cssprop];
}
else
{
if (el.currentStyle)
{//IE
if (cssprop == 'float') cssprop = 'styleFloat';
return el.currentStyle[cssprop];
}
}
}

помогла найти решение
вообще полезный у вас сайт. уже несколько решений для себя нашел.
благодарю в общем ))