2017-10-12 84 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