developer tip

자바 스크립트에서 HTML 요소의 스타일 값을 얻는 방법은 무엇입니까?

optionbox 2020. 12. 24. 23:38
반응형

자바 스크립트에서 HTML 요소의 스타일 값을 얻는 방법은 무엇입니까?


스타일 태그로 스타일이 설정된 요소에서 스타일을 검색하는 방법을 찾고 있습니다.

<style> 
#box {width: 100px;}
</style>

몸에

<div id="box"></div>

라이브러리를 사용하지 않고 바로 자바 스크립트를 찾고 있습니다.

다음을 시도했지만 계속 공백이 나타납니다.

alert (document.getElementById("box").style.width);  
alert (document.getElementById("box").style.getPropertyValue("width"));

javascript를 사용하여 스타일을 설정 한 경우에만 위의 내용을 사용할 수 있지만 스타일 태그로는 사용할 수 없다는 것을 알았습니다.


element.style속성은 다음과 같이 정의 된 경우에만 CSS 속성을 알 수 있습니다 인라인 (프로그램, 또는 요소의 스타일 속성에 정의 된) 그 요소를, 당신은 가야 계산 된 스타일을 .

브라우저 간 방식으로 그렇게하기가 쉽지는 않지만 IE는 element.currentStyle속성을 통해 자체 방식을 가지고 있으며 다른 브라우저에서 구현되는 DOM Level 2 표준 방식은 document.defaultView.getComputedStyle메서드를 통해 구현됩니다 .

두 가지 예를 들어, IE의 차이점이 element.currentStyle속성은이 두 개 이상의 단어로 구성된 CCS의 속성 이름에 액세스 기대 낙타 표기법을 (예를 들어 maxHeight, fontSize, backgroundColor, 등), 표준 방법은 단어의 속성이 대시로 구분 기대 (예 : max-height, font-size, background-color, 등).

또한 IE element.currentStyle는 지정된 단위 (예 : 12pt, 50 %, 5em)의 모든 크기를 반환하며 표준 방식은 항상 실제 크기를 픽셀 단위로 계산합니다.

얼마 전에 브라우저 간 방식으로 계산 된 스타일을 가져올 수있는 브라우저 간 함수를 만들었습니다.

function getStyle(el, styleProp) {
  var value, defaultView = (el.ownerDocument || document).defaultView;
  // W3C standard way:
  if (defaultView && defaultView.getComputedStyle) {
    // sanitize property name to css notation
    // (hypen separated words eg. font-Size)
    styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
    return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
  } else if (el.currentStyle) { // IE
    // sanitize property name to camelCase
    styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
      return letter.toUpperCase();
    });
    value = el.currentStyle[styleProp];
    // convert other units to pixels on IE
    if (/^\d+(em|pt|%|ex)?$/i.test(value)) { 
      return (function(value) {
        var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
        el.runtimeStyle.left = el.currentStyle.left;
        el.style.left = value || 0;
        value = el.style.pixelLeft + "px";
        el.style.left = oldLeft;
        el.runtimeStyle.left = oldRsLeft;
        return value;
      })(value);
    }
    return value;
  }
}

위의 함수는 일부 경우에 완벽하지 않습니다. 예를 들어 색상의 경우 표준 메서드는 rgb (...) 표기법으로 색상을 반환하고 IE에서는 정의 된대로 색상을 반환합니다.

저는 현재이 주제에 대한 기사를 작업 중입니다 . 여기 에서이 기능에 대한 변경 사항을 따를 수 있습니다 .


이제 Window.getComputedStyle ()을 사용할 수 있다고 생각합니다.

문서 MDN

var style = window.getComputedStyle(element[, pseudoElt]);

요소의 너비를 가져 오는 예 :

window.getComputedStyle(document.querySelector('#mainbar')).width

에서 jQuery를 , 당신은 할 수 있습니다 alert($("#theid").css("width")).

-jQuery를 보지 않았다면 적극 권장합니다. 그것은 많은 간단한 자바 스크립트 작업을 쉽게 만듭니다.

최신 정보

for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.


By using .css() in jquery the style tag can be accessed and modified

for example:

var color = $( this ).css( "background-color" );
  $( "#result" ).html( "That div is <span style='color:" +
    color + ";'>" + color + "</span>." );

You can make function getStyles that'll take an element and other arguments are properties that's values you want.

const convertRestArgsIntoStylesArr = ([...args]) => {
    return args.slice(1);
}

const getStyles = function () {
    const args = [...arguments];
    const [element] = args;

    let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);

    const styles = window.getComputedStyle(element);
    const stylesObj = stylesProps.reduce((acc, v) => {
        acc[v] = styles.getPropertyValue(v);
        return acc;
    }, {});

    return stylesObj;
};

Now, you can use this function like this:

const styles = getStyles(document.body, "height", "width");

OR

const styles = getStyles(document.body, ["height", "width"]);

ReferenceURL : https://stackoverflow.com/questions/2664045/how-to-get-an-html-elements-style-values-in-javascript

반응형