[javascript] 변경 : JavaScript로 CSS 속성을 호버

JavaScript를 사용하여 CSS : hover 속성을 변경하는 방법을 찾아야합니다.

예를 들어 다음 HTML 코드가 있다고 가정합니다.

<table>
  <tr>
    <td>Hover 1</td>
    <td>Hover 2</td>
  </tr>
</table>

그리고 다음 CSS 코드 :

table td:hover {
background:#ff0000;
}

JavaScript를 사용하여 <td> hover 속성을 background : # 00ff00으로 변경하고 싶습니다. JavaScript를 사용하여 스타일 배경 속성에 액세스 할 수 있습니다.

document.getElementsByTagName("td").style.background="#00ff00";

하지만 : hover에 해당하는 JavaScript를 모르겠습니다. JavaScript를 사용하여 <td>의 : hover 배경을 어떻게 변경합니까?

귀하의 도움에 감사드립니다!



답변

유사 클래스 :hover는 요소를 참조하지 않고 스타일 시트 규칙의 조건을 충족하는 모든 요소를 ​​참조합니다. 당신은 할 필요가 스타일 시트 규칙 편집 , APPEND 새 규칙을 , 또는 새로운 포함하는 새로운 스타일 시트 추가 :hover규칙을.

var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName('head')[0].appendChild(style);


답변

당신은 할 수없는 변경하거나 실제 변경 :hover자바 스크립트를 통해 선택합니다. 그러나를 사용 mouseenter하여 스타일을 변경하고 다시 되돌릴 수 있습니다 mouseleave(감사합니다, @Bryan).


답변

할 수있는 일은 개체의 클래스를 변경하고 서로 다른 호버 속성으로 두 개의 클래스를 정의하는 것입니다. 예를 들면 :

.stategood_enabled:hover  { background-color:green}
.stategood_enabled        { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled       { background-color:black}

그리고 이것은 :
JavaScript로 요소의 클래스 변경

function changeClass(object,oldClass,newClass)
{
    // remove:
    //object.className = object.className.replace( /(?:^|\s)oldClass(?!\S)/g , '' );
    // replace:
    var regExp = new RegExp('(?:^|\\s)' + oldClass + '(?!\\S)', 'g');
    object.className = object.className.replace( regExp , newClass );
    // add
    //object.className += " "+newClass;
}

changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");


답변

목적에 맞으면 CSS를 사용하지 않고 onmouseover자바 스크립트 에서 이벤트를 사용하지 않고도 호버 기능을 추가 할 수 있습니다.

다음은 코드 스 니펫입니다.

<div id="mydiv">foo</div>

<script>
document.getElementById("mydiv").onmouseover = function()
{
    this.style.backgroundColor = "blue";
}
</script>


답변

이 페이지를 7 년 늦게 찾아서 죄송합니다. 여기에이 문제를 해결할 수있는 훨씬 더 간단한 방법이 있습니다 (호버 스타일을 임의로 변경).

HTML :

<button id=Button>Button Title</button>

CSS :

.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}

자바 스크립트 :

var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');


답변

꽤 오래된 질문이므로 좀 더 현대적인 답변을 추가 할 것이라고 생각했습니다. 이제 CSS 변수가 광범위하게 지원되므로 JS 이벤트 또는 !important.

OP의 예를 들면 :

<table>
  <tr>
    <td>Hover 1</td>
    <td>Hover 2</td>
  </tr>
</table>

이제 CSS에서이 작업을 수행 할 수 있습니다.

table td:hover {
  // fallback in case we need to support older/non-supported browsers (IE, Opera mini)
  background: #ff0000;
  background: var(--td-background-color);
}

다음과 같이 javascript를 사용하여 hover 상태를 추가하십시오.

const tds = document.querySelectorAll('td');
tds.forEach((td) => {
  td.style.setProperty('--td-background-color', '#00ff00');
});

다음은 작동하는 예입니다. https://codepen.io/ybentz/pen/RwPoeqb


답변

장치가 터치를 지원하는 것을 감지하면 모든 :hover속성 을 대체하는 것이 좋습니다 :active. 이렇게 할 때이 함수를 호출하십시오.touch()

   function touch() {
      if ('ontouchstart' in document.documentElement) {
        for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
          var sheet = document.styleSheets[sheetI];
          if (sheet.cssRules) {
            for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
              var rule = sheet.cssRules[ruleI];

              if (rule.selectorText) {
                rule.selectorText = rule.selectorText.replace(':hover', ':active');
              }
            }
          }
        }
      }
    }