2017-10-12 9 views
0

돔 준비가 끝나면 마우스가 움직이고 부모 div에 "has-hover"클래스가 연결되어 있는지 감지합니다.CSS : 동적으로 추가 된 클래스가있는 요소에서 호버가 작동하지 않습니다.

내부에는 두 개의 라벨이 있습니다. 첫 번째 요소는 부모 div의 "has-hover"클래스에 연결된 호버 상태를 가지며, 이는 달성하고자하는 기능입니다.

두 번째 레이블에는 마우스 오버 상태가 바로 붙어 있습니다.

왜 두 번째 레이블에서 호버 상태가 작동하지만 첫 번째 레이블에서는 작동하지 않습니다 ??

감사합니다.

function watchForHover() { 
 
\t var div = $(".div"); 
 
    var hasHoverClass = false; 
 

 
\t function enableHover() { 
 
    \t if (hasHoverClass) return; 
 
\t \t div.addClass("has-hover"); 
 
\t \t hasHoverClass = true; 
 
\t }; 
 
    
 
\t document.addEventListener("mousemove", enableHover, true); 
 
}; 
 

 
watchForHover();
label { 
 
    width: 70px; 
 
    height: 70px; 
 
    margin: 5px; 
 
    color: white; 
 
    background-color: red; 
 
    transition: all 0.3s; 
 
    display: block; 
 
} 
 
.has-hover { 
 
    label:first-child:hover { 
 
    opacity: 0.5; 
 
    } 
 
} 
 
label:nth-child(2):hover { 
 
    opacity: 0.5; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="div"> 
 
<label>label 1</label> 
 
<label>label 2</label> 
 
</div>

+0

내가, 당신이 다음에 선택기를 단순화 할 수 있었던 것처럼 착각 보이는거야하지 않는 : hover', 그리고 '위로 가져 가면 때 스타일 규칙이 적용됩니다 : .has - 호버 라벨' label' 부모 클래스'.div'가 클래스'.has-hover'를 가지고있는 한 – UncaughtTypeError

+0

Thanks @ UncaughtTypeError. 저는 예제를 위해서 자식 의사 선택기를 사용했습니다. 만약 내가 그들을 제거하고 그냥 거기 떠날 .has - hover 선택기 중 하나를 작동하지 않을거야 ... 거기에 대한 설명이 무엇입니까? – metaskopia

+0

방금 ​​시도했습니다 .has-hover 레이블 : 호버 { 불투명도 : .5; }'코드 스 니펫 예제를 사용하여 브라우저 IDE에서 예상대로 작동했습니다. 아니면 다른 것을 성취하려고합니까? – UncaughtTypeError

답변

0

저쪽 CSS에서하지 둥지 규칙 있습니다. 만약 그렇게하지 않으려한다면 SASS와 같은 전 처리기를 사용해야 할 것입니다.

function watchForHover() { 
 
\t var div = $(".div"); 
 
    var hasHoverClass = false; 
 

 
\t function enableHover() { 
 
    \t if (hasHoverClass) return; 
 
\t \t div.addClass("has-hover"); 
 
\t \t hasHoverClass = true; 
 
\t }; 
 
    
 
\t document.addEventListener("mousemove", enableHover, true); 
 
}; 
 

 
watchForHover();
label { 
 
    width: 70px; 
 
    height: 70px; 
 
    margin: 5px; 
 
    color: white; 
 
    background-color: red; 
 
    transition: all 0.3s; 
 
    display: block; 
 
} 
 
.has-hover label:first-child:hover { 
 
    opacity: 0.5; 
 
    } 
 
label:nth-child(2):hover { 
 
    opacity: 0.5; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="div"> 
 
<label>label 1</label> 
 
<label>label 2</label> 
 
</div>

+0

내 잘못입니다. SASS를 사용했지만 그 사실을 잊어 버렸습니다. 감사! – metaskopia