기본 코드 :
<! docType html> <html lang = "en"> <head> <meta charset = "utf-8"> <title> 문서 </title> <style> div {color : yellow; } </style> </head> <body> <div> 이것은 div </div> </body> </html>입니다1. 요소 속성을 사용하여 가져옵니다
<cript> var div = document.getElementsByTagName ( "div") [0]; Console.log (div.style.color); // ""console.log (div.style.backgroundColor); // 빨간색 </script>
요소 속성은 인라인 스타일 만 얻을 수 있고 <style> 태그로 스타일을 얻을 수 없으며 외부 스타일을 얻을 수 없습니다.
element.style은 요소의 속성이므로 요소의 표시를 무시하기 위해 속성을 재 할당 할 수 있습니다.
<cript> var div = document.getElementsByTagName ( "div") [0]; Div.Style [ 'Background-Color'] = "Green"; Console.log (div.style.backgroundcolor); // 녹색 </script>
2. GetComputedStyle 및 CurrentStyle을 통해 스타일을 얻으십시오
GetComputedStyle의 사용 환경은 Chrome/Safari/Firefox IE 9,10,11입니다
<cript> var div = document.getElementsByTagName ( "div") [0]; var styleobj = window.getComputedStyle (div, null); Console.log (StyleObj.backgroundColor); // red console.log (styleobj.color); // Yellow </script>
CurrentStyle은 IE에서 완벽하게 지원할 수 있으며 Chrome은 지원하지 않으며 FF는 지원하지 않습니다.
<cript> var div = document.getElementsByTagName ( "div") [0]; var styleobj = div.currentStyle; Console.log (StyleObj.backgroundColor); // red console.log (styleobj.color); // Yellow </script>
3. Ele.Style과 GetComputedStyle 또는 CurrentStyle의 차이
3.1ele.Style은 읽기 쓰기이며 GetComputedStyle 및 CurrentStyle은 읽기 전용입니다
3.2 ELE.Style은 라인의 스타일 속성에 CSS 스타일을 설정할 수 있으며 GetComputedStyle 및 CurrentStyle도 다른 기본값을 얻을 수 있습니다.
3.3 ELE.Style 스타일은 반드시 최종 스타일이 아니라 스타일 속성에서 스타일을 얻는 반면 다른 두 사람은 요소의 최종 CSS 스타일을 얻습니다.
4. 스타일 호환성 작문을 얻으십시오
<cript> // 비 라인 스타일 (스타일 태그의 스타일 또는 링크 CSS 파일의 스타일), obj는 요소입니다. attr은 스타일 이름 함수 getstyle (obj, attr) {// ie if (obj.currentStyle) {return obj.currentStyle [attr]; // 함수가 통과하는 attr은 문자열이므로 []를 사용하여 값을 가져와야합니다} else {// nonie return Window.getComputedStyle (obj, false) [attr]; }} /* CSS 속성을 가져 오거나 설정하십시오* / function css (obj, attr, value) {if (arguments.length == 2) {return getStyle (obj, attr); } else {obj.style [attr] = value; }} </script>5.window.getComputedStyle (ele [, pseudoelt]);
두 번째 매개 변수가 null 또는 생략되면 ELE 인 CSSSTYLEDECLARATION 객체를 가져옵니다.
의사 클래스 인 경우 의사 클래스의 CSSStyledEclaration 객체가 얻어집니다.
<style> div {너비 : 200px; 높이 : 200px; 배경색 :#fc9; 글꼴 크기 : 20px; 텍스트 정렬 : 센터; } div : {컨텐츠 후 : "이것은 이후입니다"; 디스플레이 : 블록; 너비 : 100px; 높이 : 100px; 배경색 :#F93; 여백 : 0 Auto; 라인 높이 : 50px; }. btn.onclick = function () {var div = document.querySelector ( '#mydiv'); var styleobj = wind console.log (styleobj [ 'width']); } </script> </body>6. GetPropertyValue cssstyledeclaration 객체에서 지정된 속성 값을 가져옵니다.
<cript> var div = document.getElementsByTagName ( "div") [0]; var styleobj = window.getComputedStyle (div, null); console.log (styleobj.getPropertyValue ( "background-color")); </script>
getPropertyValue (PropertyName)의 PropertyName; 낙타 표현이 될 수 없습니다
obj.currentStyle [ 'margin-left']가 작동합니다
obj.currentStyle [ 'Marginleft']가 작동합니다
window.getComputedStyle (obj, null) [ '마진-왼쪽'] 작동합니다
window.getComputedStyle (OBJ, NULL) [ 'Marginleft']가 작동합니다
window.getComputedStyle (obj, null) .getProperTyValue ( 'margin-left') 유효합니다
window.getComputedStyle (OBJ, NULL) .GetProperTyValue ( 'Marginleft')가 잘못되었습니다
obj.currentStyle.width가 유효합니다
obj.currentStyle.background 색상이 잘못되었습니다
obj.currentStyle.backgroundColor Works
window.getComputedStyle (OBJ, NULL) .WIDTH 유효합니다
Window.getComputedStyle (OBJ, NULL) .Background-Color Invalid
Window.getComputedStyle (OBJ, NULL) .BackgroundColor Works
요약하면 "-"가있는 속성은 직접 지적 할 수 없으므로 처리 할 getPropertyValue 메소드가 있지만 []를 사용하여 GetPropertyValue를 대체 할 수 있습니다.
7. DefaultView
많은 온라인 데모 코드에서 GetComputedStyle은 Document.DefaultView 객체를 통해 호출됩니다. 대부분의 경우 창 객체를 통해 직접 호출 할 수 있으므로 필요하지 않습니다. 그러나 Firefox3.6 (iframe)의 서브 프레임 내부의 스타일에 액세스하는 DefaultView를 사용해야하는 상황이 있습니다.
JS의 스타일 (권장)을 얻는 위의 간단한 구현 방법은 내가 공유하는 모든 컨텐츠입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.