2017-10-12 83 views
0

Dom準備好後,我檢測鼠標是否移動並將類「has-hover」附加到父div。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',並懸停在'當你的風格規則將適用標籤',只要父'.div'有類'.has-hover' – UncaughtTypeError

+0

謝謝@UncaughtTypeError。爲了示例,我使用了子僞選擇器。如果我刪除它們,只是離開那裏。懸停選擇器它不會工作...是否有解釋呢? – metaskopia

+0

我剛試過'.has-hover label:hover { opacity:.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