JavaScript получить стили - PullRequest
6 голосов
/ 13 ноября 2010

Можно ли получить ВСЕ стили для объекта, используя JavaScript? Что-то вроде:


main.css
-------
#myLayer {
  position: absolute;
  width: 200px;
  height: 100px;
  color: #0000ff;
}

main.js
-------
var ob = document.getElementById("myLayer");
var pos = ob.(getPosition);
// Pos should equal "absolute" but
// ob.style.position would equal null
// any way to get absolute?


Ответы [ 3 ]

18 голосов
/ 13 ноября 2010

Вы говорите о том, что известно как Computed Style , ознакомьтесь со следующей статьей о том, как его получить:

Из последней статьи приведена функция:

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

Как его использовать:

CSS:

/* Element CSS*/
div#container{
    font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif;
}

JS:

var elementFontSize = getStyle(document.getElementById("container"), "font-size");
2 голосов
/ 28 февраля 2013

Polyfill для получения текущего стиля CSS элемента с использованием javascript ... Посетите ссылку для получения дополнительной информации

/**
* @desc : polyfill for getting the current CSS style of the element
* @param : elem - The Element for which to get the computed style.
* @param : prop - The Property for which to get the value
* @returns : The returned style value of the element
**/
var getCurrentStyle = function (ele, prop) {

var currStyle;
if (!window.getComputedStyle) {
    currStyle = ele.currentStyle[prop];
} else {
    currStyle = window.getComputedStyle(ele).getPropertyValue(prop);
}

return currStyle;
}


/** How to use **/
var element = document.getElementById("myElement");
getCurrentStyle(element, "width"); // returns the width value   
1 голос
/ 13 ноября 2010

Вы можете использовать:

var ob = document.getElementById("myLayer");
var pos = ob.style.position;

Каждое свойство CSS имеет свою собственную объектную модель. Обычно те свойства CSS, которые содержат '-', пишутся с использованием модели Java.

Например:

//getting background-color property
var ob = document.getElementById("myLayer");
var color = ob.style.backgroundColor;

Если вы хотите получить все свойства css, определенные для объекта, вам придется перечислять их одно за другим, потому что даже если вы не установили свойство в таблице стилей, объект будет иметь его с значение по умолчанию.

...