developer tip

자바 스크립트로 CSS 값 변경

optionbox 2020. 8. 18. 07:39
반응형

자바 스크립트로 CSS 값 변경


자바 스크립트로 인라인 CSS 값을 설정하는 것은 쉽습니다. 너비를 변경하고 다음과 같은 html이있는 경우 :

<div style="width: 10px"></div>

내가해야 할 일은 다음과 같습니다.

document.getElementById('id').style.width = value;

인라인 스타일 시트 값을 변경합니다. 인라인 스타일이 스타일 시트를 재정의하기 때문에 일반적으로 이것은 문제가되지 않습니다. 예:

<style>
   #tId {
      width: 50%;
   }
</style>

<div id="tId"></div>

이 자바 스크립트 사용 :

document.getElementById('tId').style.width = "30%";

다음을 얻습니다.

<style>
   #tId {
      width: 50%;
   }
</style>

<div id="tId" style="width: 30%";></div>

인라인 값을 변경하고 싶지 않을뿐만 아니라 너비를 설정하기 전에 검색하면 다음과 같은 경우 문제가됩니다.

<div id="tId"></div>

반환 된 값은 Null이므로 논리를 수행하기 위해 너비를 알아야하는 Javascript가있는 경우 (특정 값이 아니라 너비를 1 % 늘림) 문자열 "50 %"가 예상 될 때 Null이 반환됩니다. "실제로 작동하지 않습니다.

그래서 내 질문 : 인라인에 있지 않은 CSS 스타일의 값이 있습니다. 어떻게 이러한 값을 얻을 수 있습니까? ID가 주어지면 인라인 값 대신 스타일을 어떻게 수정할 수 있습니까?


좋아, 한 번에 작은 스타일의 모든 요소를 ​​효율적으로 변경하도록 전역 CSS를 변경하려는 것 같습니다. 최근에 Shawn Olson 튜토리얼 에서 직접이 작업을 수행하는 방법을 배웠습니다 . 여기에서 그의 코드를 직접 참조 할 수 있습니다 .

요약은 다음과 같습니다.

를 통해 스타일 시트검색 할 수 있습니다 document.styleSheets. 이것은 실제로 페이지에있는 모든 스타일 시트의 배열을 반환하지만 document.styleSheets[styleIndex].href속성 을 통해 어떤 스타일 시트에 있는지 알 수 있습니다 . 편집 할 스타일 시트를 찾으면 규칙 배열을 가져와야합니다. 이를 IE에서는 "규칙"이라고하고 다른 대부분의 브라우저에서는 "cssRules"라고합니다. CSSRule무엇인지 알려주는 방법 selectorText속성에 의해 결정 됩니다. 작업 코드는 다음과 같습니다.

var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText;  //maybe '#tId'
var value = rule.value;            //both selectorText and value are settable.

이것이 어떻게 작동하는지 알려주고 오류가 있으면 의견을 말하십시오.


부디! w3 ( http://www.quirksmode.org/dom/w3c_css.html ) 에게 물어 보세요! 아니면 실제로 5 시간이 걸렸습니다 ...하지만 여기 있습니다!

function css(selector, property, value) {
    for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles
        //Try add rule
        try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
        } catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE
    }
}

이 기능은 정말 사용하기 쉽습니다 .. 예 :

<div id="box" class="boxes" onclick="css('#box', 'color', 'red')">Click Me!</div>
Or:
<div class="boxes" onmouseover="css('.boxes', 'color', 'green')">Mouseover Me!</div>
Or:
<div class="boxes" onclick="css('body', 'border', '1px solid #3cc')">Click Me!</div>

오..


편집 : @ user21820이 답변에 설명했듯이 페이지의 모든 스타일 시트를 변경하는 것이 약간 불필요 할 수 있습니다. 다음 스크립트는 IE5.5 및 최신 Google Chrome에서 작동하며 위에서 설명한 css () 함수 만 추가합니다.

(function (scope) {
    // Create a new stylesheet in the bottom
    // of <head>, where the css rules will go
    var style = document.createElement('style');
    document.head.appendChild(style);
    var stylesheet = style.sheet;
    scope.css = function (selector, property, value) {
        // Append the rule (Major browsers)
        try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length);
        } catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9)
        } catch(err) {console.log("Couldn't add style");}} // (alien browsers)
    }
})(window);

답변에서 코드를 수집하여 FF 25에서 잘 실행되는 것 같은이 함수를 작성했습니다.

function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
  /* returns the value of the element style of the rule in the stylesheet
  *  If no value is given, reads the value
  *  If value is given, the value is changed and returned
  *  If '' (empty string) is given, erases the value.
  *  The browser will apply the default one
  *
  * string stylesheet: part of the .css name to be recognized, e.g. 'default'
  * string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
  * string style: camelCase element style, e.g. 'fontSize'
  * string value optionnal : the new value
  */
  var CCSstyle = undefined, rules;
  for(var m in document.styleSheets){
    if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
     rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
     for(var n in rules){
       if(rules[n].selectorText == selectorText){
         CCSstyle = rules[n].style;
         break;
       }
     }
     break;
    }
  }
  if(value == undefined)
    return CCSstyle[style]
  else
    return CCSstyle[style] = value
}

이것은 브라우저에서 이해하지 못하더라도 JS에서 사용될 CSS에 값을 넣는 방법입니다. 예를 들어 스크롤 테이블의 tbody에 대한 maxHeight.

전화 :

CCSStylesheetRuleStyle('default', "#mydiv", "height");

CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");


다른 솔루션이 문서의 전체 스타일 시트 목록을 통과하는 이유를 모르겠습니다. 이렇게하면 각 스타일 시트에 새 항목이 만들어 지므로 비효율적입니다. 대신 새 스타일 시트를 추가하고 원하는 CSS 규칙을 거기에 추가하기 만하면됩니다.

style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
    try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
    catch(err){}
}

Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.


I don't have rep enough to comment so I'll format an answer, yet it is only a demonstration of the issue in question.

It seems, when element styles are defined in stylesheets they are not visible to getElementById("someElement").style

This code illustrates the issue... Code from below on jsFiddle.

In Test 2, on the first call, the items left value is undefined, and so, what should be a simple toggle gets messed up. For my use I will define my important style values inline, but it does seem to partially defeat the purpose of the stylesheet.

Here's the page code...

<html>
  <head>
    <style type="text/css">
      #test2a{
        position: absolute;
        left: 0px;
        width: 50px;
        height: 50px;
        background-color: green;
        border: 4px solid black;
      }
      #test2b{
        position: absolute;
        left: 55px;
        width: 50px;
        height: 50px;
        background-color: yellow;
        margin: 4px;
      }
    </style>
  </head>
  <body>

  <!-- test1 -->
    Swap left positions function with styles defined inline.
    <a href="javascript:test1();">Test 1</a><br>
    <div class="container">
      <div id="test1a" style="position: absolute;left: 0px;width: 50px; height: 50px;background-color: green;border: 4px solid black;"></div>
      <div id="test1b" style="position: absolute;left: 55px;width: 50px; height: 50px;background-color: yellow;margin: 4px;"></div>
    </div>
    <script type="text/javascript">
     function test1(){
       var a = document.getElementById("test1a");
       var b = document.getElementById("test1b");
       alert(a.style.left + " - " + b.style.left);
       a.style.left = (a.style.left == "0px")? "55px" : "0px";
       b.style.left = (b.style.left == "0px")? "55px" : "0px";
     }
    </script>
  <!-- end test 1 -->

  <!-- test2 -->
    <div id="moveDownThePage" style="position: relative;top: 70px;">
    Identical function with styles defined in stylesheet.
    <a href="javascript:test2();">Test 2</a><br>
    <div class="container">
      <div id="test2a"></div>
      <div id="test2b"></div>
    </div>
    </div>
    <script type="text/javascript">
     function test2(){
       var a = document.getElementById("test2a");
       var b = document.getElementById("test2b");
       alert(a.style.left + " - " + b.style.left);
       a.style.left = (a.style.left == "0px")? "55px" : "0px";
       b.style.left = (b.style.left == "0px")? "55px" : "0px";
     }
    </script>
  <!-- end test 2 -->

  </body>
</html>

I hope this helps to illuminate the issue.

Skip


You can get the "computed" styles of any element.

IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".

You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).

That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.

The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value)

Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:

<div style="width:50%">....</div>

This simple 32 lines gist lets you identify a given stylesheet and change its styles very easily:

var styleSheet = StyleChanger("my_custom_identifier");
styleSheet.change("darkolivegreen", "blue");

I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.

If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth and element.offsetHeight.


Perhaps try this:

function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
  var CCSstyle = undefined, rules;
  for(var m in document.styleSheets){
    if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
     rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
     for(var n in rules){
       if(rules[n].selectorText == selectorText){
         CCSstyle = rules[n].style;
         break;
       }
     }
     break;
    }
  }
  if(value == undefined)
    return CCSstyle[style]
  else
    return CCSstyle[style] = value
}

참고URL : https://stackoverflow.com/questions/566203/changing-css-values-with-javascript

반응형