>  기사  >  웹 프론트엔드  >  Js에서 스타일을 얻는 일반적인 방법

Js에서 스타일을 얻는 일반적인 방법

php中世界最好的语言
php中世界最好的语言원래의
2017-11-28 15:26:462503검색

JS에서 CSS를 작동하려면 가장 중요한 것은 스타일을 얻는 것입니다. 다음은 참고용으로 JS에서 스타일을 얻는 가장 일반적인 방법에 대한 기사입니다.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    div{
      color:yellow;
    }
  </style>
</head>
<body>
  <div style="width:100px;height:100px;background-color:red">This is div</div>
</body>
</html>

element.style 속성을 사용하여 가져옵니다.

<script>
  var div = document.getElementsByTagName("div")[0];
  console.log(div.style.color); //""
  console.log(div.style.backgroundColor); //red
</script>

element.style 속성은 c9ccee2e6ea535a969eb3f532ad9fe89 태그의 스타일이나 외부 스타일이 아닌 인라인 스타일만 가져올 수 있습니다. 요소 속성을 사용하면 속성을 다시 할당하여 요소 표시를 변경할 수 있습니다.

<script>
    var div = document.getElementsByTagName("div")[0];
    div.style[&#39;background-color&#39;] = "green";
    console.log(div.style.backgroundColor); //green
  </script>

2. getCompulatedStyle 및 currentStyle을 통해 스타일 가져오기

getComputeStyle의 사용 환경은 chrome/safari/firefox입니다. IE 9,10,11

<script>
  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에서는 지원하지 않습니다. 지원하지 않습니다

<script>
    var div = document.getElementsByTagName("div")[0];
    var styleObj = div.currentStyle;
    console.log(styleObj.backgroundColor); //red
    console.log(styleObj.color); //yellow
  </script>

3 ele.style과 getCompulatedStyle 또는 currentStyle

3.1의 차이점은 ele.style은 읽기-쓰기이고, getCompulatedStyle과 currentStyle은 읽기 전용입니다

3.2 ele.style은 CSS 스타일만 가져올 수 있습니다. 인라인 스타일 속성에 설정됩니다. 그리고 getCompulatedStyle 및 currentStyle은 다른 기본값을 얻을 수도 있습니다

3.3 ele.style은 반드시 최종 스타일이 아닌 스타일 속성에서 스타일을 가져오는 반면, 다른 두 개는 요소의 최종 CSS 스타일을 가져옵니다

4. 스타일 호환성 작성 방법 가져오기

<script>
    //获取非行间样式(style标签里的样式或者link css文件里的样式),obj是元素,attr是样式名
    function getStyle(obj,attr){
       //针对IE
       if(obj.currentStyle){
         return obj.currentStyle[attr];               //由于函数传过来的attr是字符串,所以得用[]来取值
       }else{
         //针对非IE
         return window.getComputedStyle(obj,false)[attr];
       }
    }
    function css(obj,attr,value){
       if(arguments.length == 2){
         return getStyle(obj,attr);
       }else{   
         obj.style[attr] = value;
       }
    }
  </script>
 
.window.getComputedStyle(ele[,pseudoElt]);

두 번째 매개 변수가 null이거나 생략되면 ele의 CSSStyleDeclaration 개체를 가져옵니다.

가상 클래스인 경우 해당 의사 클래스의 CSSStyleDeclaration 개체를 가져옵니다.

<style>
div{
  width:200px;
  height:200px;
  background-color:#FC9;
  font-size:20px;
  text-align:center;  
}
div:after{
  content:"This is after";
  display:block;
  width:100px;
  height:100px;
  background-color:#F93;
  margin:0 auto;
  line-height:50px;  
}
</style>
<body>
  <div id=&#39;myDiv&#39;>
    This is div
  </div> 
  <input id=&#39;btn&#39; type="button" value=&#39;getStyle&#39;/> 
  <script>
    var btn = document.querySelector(&#39;#btn&#39;);
    btn.onclick = function(){
      var div = document.querySelector(&#39;#myDiv&#39;);
      var styleObj = window.getComputedStyle(div,&#39;after&#39;);
      console.log(styleObj[&#39;width&#39;]);
    }
  </script>
</body>


getPropertyValue CSSStyleDeclaration 객체에 지정된 속성값

<script>
    var div = document.getElementsByTagName("div")[0];
    var styleObj = window.getComputedStyle(div,null);
    console.log(styleObj.getPropertyValue("background-color"));
</script>
 
getPropertyValue(propertyName);中的propertyName不能是驼峰式表示
obj.currentStyle[&#39;margin-left&#39;] 有效
obj.currentStyle[&#39;marginLeft&#39;]  有效   
window.getComputedStyle(obj,null)[&#39;margin-left&#39;]  有效
window.getComputedStyle(obj,null)[&#39;marginLeft&#39;]  有效
window.getComputedStyle(obj,null).getPropertyValue(&#39;margin-left&#39;)  有效
window.getComputedStyle(obj,null).getPropertyValue(&#39;marginLeft&#39;)   无效
obj.currentStyle.width   有效
obj.currentStyle.background-color 无效
obj.currentStyle.backgroundColor  有效
window.getComputedStyle(obj,null).width  有效
window.getComputedStyle(obj,null).background-color  无效
window.getComputedStyle(obj,null).backgroundColor 有效

정리하자면 "-"가 붙은 속성은 직접 클릭이 불가능해서 getProperty

Value 메소드

를 사용하여 처리할 수 있지만, [] getPropertyValue7.defaultView

많은 온라인 데모 코드에서 getComputeStyle은 document.defaultView 개체를 통해 호출됩니다. 대부분의 경우

window 개체

를 통해 직접 호출할 수 있으므로 이는 필요하지 않습니다. 하지만 Firefox3.6에서 서브프레임의 스타일(iframe)에 액세스하기 위해 defaultView를 사용해야 하는 상황이 있습니다.이 사례를 읽고 나면 이 방법을 마스터했다고 생각합니다. 더 흥미로운 정보를 보려면 주의하세요. PHP 중국어 웹사이트 기사의 기타 관련 주제!


관련 읽기:

CSS를 사용하여 HTML에서 div를 숨기는 방법


Vue+CSS3을 사용하여 대화형 효과를 만드는 방법


이모지 표현이 불가능한 버그를 해결하는 방법 프런트엔드에서 전송됨

위 내용은 Js에서 스타일을 얻는 일반적인 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.