programing tip

JavaScript에서 CSS 의사 클래스 규칙 설정

itbloger 2020. 7. 18. 10:37
반응형

JavaScript에서 CSS 의사 클래스 규칙 설정


JavaScript에서 의사 클래스 선택기 (예 : : link, : hover 등)의 CSS 규칙을 변경하는 방법을 찾고 있습니다.

CSS 코드와 유사합니다 : a:hover { color: red }JS.

다른 곳에서는 답을 찾지 못했습니다. 이것이 브라우저가 지원하지 않는 것임을 아는 사람도 도움이 될 것입니다.


인라인 style = "..."속성에 의사 클래스를 가질 수없는 것과 같은 방식으로 특정 요소에만 의사 클래스의 스타일을 지정할 수 없습니다 (선택기가 없으므로).

스타일 시트를 변경하여 (예 : 규칙 추가)이를 수행 할 수 있습니다.

#elid:hover { background: red; }

영향을 줄 각 요소에 고유 ID가 있다고 가정하면 선택할 수 있습니다.

이론적으로 원하는 문서는 http://www.w3.org/TR/DOM-Level-2-Style/Overview.html 이며 다음과 같은 구문을 사용하여 (기존의 내장 또는 링크 된 스타일 시트를 제공 할 수 있음) 의미합니다.

document.styleSheets[0].insertRule('#elid:hover { background-color: red; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';

물론 IE에는 자체 구문이 필요합니다.

document.styleSheets[0].addRule('#elid:hover', 'background-color: red', 0);
document.styleSheets[0].rules[0].style.backgroundColor= 'red';

오래된 브라우저와 작은 브라우저는 어느 구문도 지원하지 않을 수 있습니다. 다이내믹 한 스타일 시트 인증은 옳고, 거의 필요 없으며, 역사적으로 번거로운 일이기 때문에 거의 수행되지 않습니다.


JS에서 스타일 시트를 조작하기위한 유효한 유스 케이스가 있다고 생각 하기 때문에 작은 라이브러리를 함께 던졌습니다 . 이유 :

  • 계산하거나 검색해야하는 스타일 설정 (예 : 쿠키에서 사용자가 선호하는 글꼴 크기 설정)
  • 특히 UI 위젯 / 플러그인 개발자를위한 행동 적 (미학적이 아닌) 스타일 설정. 탭, 캐 러셀 등은 종종 작동하기 위해 몇 가지 기본 CSS를 필요로 합니다. 핵심 기능에 대한 스타일 시트를 요구 하지 않아야 합니다.
  • CSS 규칙은 현재 및 미래의 모든 요소에 적용되며 Firebug / Developer Tools에서 볼 때 HTML을 어지럽히 지 않기 때문에 인라인 스타일보다 좋습니다.

크로스 브라우저에 대응하는 기능 :

addCssRule = function(/* string */ selector, /* string */ rule) {
  if (document.styleSheets) {
    if (!document.styleSheets.length) {
      var head = document.getElementsByTagName('head')[0];
      head.appendChild(bc.createEl('style'));
    }

    var i = document.styleSheets.length-1;
    var ss = document.styleSheets[i];

    var l=0;
    if (ss.cssRules) {
      l = ss.cssRules.length;
    } else if (ss.rules) {
      // IE
      l = ss.rules.length;
    }

    if (ss.insertRule) {
      ss.insertRule(selector + ' {' + rule + '}', l);
    } else if (ss.addRule) {
      // IE
      ss.addRule(selector, rule, l);
    }
  }
};

내 트릭은 속성 선택기를 사용하고 있습니다. 자바 스크립트로 속성을 쉽게 설정할 수 있습니다.

CSS

.class{ /*normal css... */}
.class[special]:after{ content: 'what you want'}

자바 스크립트

  function setSpecial(id){ document.getElementById(id).setAttribute('special', '1'); }

html

<element id='x' onclick="setSpecial(this.id)"> ...  

CSS를 템플릿 문자열에 넣으십시오.

const cssTemplateString = `.foo:[psuedoSelector]{prop: value}`;

그런 다음 스타일 요소를 만들고 문자열을 스타일 태그에 넣고 문서에 첨부하십시오.

const styleTag = document.createElement("style");
styleTag.innerHTML = cssTemplateString;
document.head.insertAdjacentElement('beforeend', styleTag);

Specificity will take care of the rest. Then you can remove and add style tags dynamically. This is a simple alternative to libraries and messing with the stylesheet array in the DOM. Happy Coding!


There is another alternative. Instead of manipulating the pseudo-classes directly, create real classes that model the same things, like a "hover" class or a "visited" class. Style the classes with the usual "." syntax and then you can use JavaScript to add or remove classes from an element when the appropriate event fires.


Instead of directly setting pseudo-class rules with javascript, you can set the rules differently in different CSS files, and then use Javascript to switch one stylesheet off and to switch another on. A method is described at A List Apart (qv. for more detail).

Set up the CSS files as,

<link rel="stylesheet" href="always_on.css">
<link rel="stylesheet" title="usual" href="preferred.css"> <!-- on by default -->
<link rel="alternate stylesheet" title="strange" href="alternate.css"> <!-- off by default -->

And then switch between them using javascript:

function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")<i>); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
}

As already stated this is not something that browsers support.

If you aren't coming up with the styles dynamically (i.e. pulling them out of a database or something) you should be able to work around this by adding a class to the body of the page.

The css would look something like:

a:hover { background: red; }
.theme1 a:hover { background: blue; }

And the javascript to change this would be something like:

// Look up some good add/remove className code if you want to do this
// This is really simplified

document.body.className += " theme1";  

Switching stylesheets in and out is the way to do it. Here is a library to build stylesheets dynamically, so you can set styles on the fly:

http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/


In jquery you can easily set hover pseudo classes.

$("p").hover(function(){
$(this).css("background-color", "yellow");
}, function(){
$(this).css("background-color", "pink");
});

If you use REACT , There is something called radium. It is so useful here :

  • Add handlers to props if interactive styles are specified, e.g. onMouseEnter for :hover, wrapping existing handlers if necessary

  • If any of the handlers are triggered, e.g. by hovering, Radium calls setState to update a Radium-specific field on the components state object

  • On re-render, resolve any interactive styles that apply, e.g. :hover, by looking up the element's key or ref in the Radium-specific state

here is a solution including two functions: addCSSclass adds a new css class to the document, and toggleClass turns it on

The example shows adding a custom scrollbar to a div

// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
  var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
  var add = (arguments.length > 2 ? newState : (elem.className.match(matchRegExp) === null));

  elem.className = elem.className.replace(matchRegExp, ''); // clear all
  if (add) elem.className += ' ' + theClass;
}

function addCSSclass(rules) {
  var style = document.createElement("style");
  style.appendChild(document.createTextNode("")); // WebKit hack :(
  document.head.appendChild(style);
  var sheet = style.sheet;

  rules.forEach((rule, index) => {
    try {
      if ("insertRule" in sheet) {
        sheet.insertRule(rule.selector + "{" + rule.rule + "}", index);
      } else if ("addRule" in sheet) {
        sheet.addRule(rule.selector, rule.rule, index);
      }
    } catch (e) {
      // firefox can break here          
    }
    
  })
}

let div = document.getElementById('mydiv');
addCSSclass([{
    selector: '.narrowScrollbar::-webkit-scrollbar',
    rule: 'width: 5px'
  },
  {
    selector: '.narrowScrollbar::-webkit-scrollbar-thumb',
    rule: 'background-color:#808080;border-radius:100px'
  }
]);
toggleClass(div, 'narrowScrollbar', true);
<div id="mydiv" style="height:300px;width:300px;border:solid;overflow-y:scroll">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus
  a diam volutpat, ullamcorper justo eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit
  nec sodales sodales. Etiam eget dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui. Lorem ipsum dolor sit amet, consectetur
  adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus a diam volutpat, ullamcorper justo
  eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit nec sodales sodales. Etiam eget
  dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui.
</div>

참고URL : https://stackoverflow.com/questions/311052/setting-css-pseudo-class-rules-from-javascript

반응형