我有一个嵌套注释的集合.我的目标是在分别悬停每个评论时显示“回复”选项.这意味着我不希望“回复”选项显示在我的鼠标悬停的评论的父母/兄弟/孩子.
我发现的唯一类似的问题是:Can I control CSS selection for :hover on nested elements?我甚至不确定他的需求是一样的,另外还有一些谜语似乎不起作用.
我准备了一个fiddle,所以你最好看看我的意思:
.comment { padding: 10px; border: 1px solid black; margin-top: 10px; } .text {} .comment:hover > .reply { display: inline-block; } .reply { display: none; } .children-comments { margin-left: 50px; margin-top: 10px; }
<div class="comment"> <a class="text">wohoo</a> <a class="reply">reply</a> <div class="children-comments"> <div class="comment"> <a class="text">wohoo</a> <a class="reply">reply</a> <div class="children-comments"> </div> </div> <div class="comment"> <a class="text">wohoo</a> <a class="reply">reply</a> <div class="children-comments"> <div class="comment"> <a class="text">wohoo</a> <a class="reply">reply</a> <div class="children-comments"> <div class="comment"> <a class="text">wohoo</a> <a class="reply">reply</a> <div class="children-comments"> </div> </div> </div> </div> </div> </div> <div class="comment"> <a class="text">wohoo</a> <a class="reply">reply</a> <div class="children-comments"> </div> </div> </div> </div>
请注意,使用>在选择器中确实可以忽略同级元素,但仍然选择父元素.换句话说,无论你悬停哪个评论,他们的父母都会一直显示“回复”选项.
解决方法
你最好的选择是改变标记一点,并添加一个包装:
<div class="comment"> <div class="content"> <!-- Here --> <a class="text">wohoo</a> <a class="reply">reply</a> </div>
通过添加内容的div包装器,您可以使用.content:hover> .回复
例:
.comment { padding: 10px; border: 1px solid black; margin-top: 10px; } .text {} .content:hover > .reply { display: inline-block; } .reply { display: none; } .children-comments { margin-left: 50px; margin-top: 10px; }
<div class="comment"> <div class="content"> <a class="text">wohoo</a> <a class="reply">reply</a> </div> <div class="children-comments"> <div class="comment"> <div class="content"> <a class="text">wohoo</a> <a class="reply">reply</a> </div> <div class="children-comments"> <div class="comment"> <div class="content"> <a class="text">wohoo</a> <a class="reply">reply</a> </div> </div> <div class="children-comments"> <div class="comment"> <div class="content"> <a class="text">wohoo</a> <a class="reply">reply</a> </div> <div class="children-comments"> <div class="comment"> <div class="content"> <a class="text">wohoo</a> <a class="reply">reply</a> </div> <div class="children-comments"> </div> </div> </div> </div> </div> </div> <div class="comment"> <div class="content"> <a class="text">wohoo</a> <a class="reply">reply</a> <div class="children-comments"> </div> </div> </div> </div> </div>
但是,您也可以通过使用定位样式将包装器扩展到整个注释块(不仅仅是评论的内容).例如:
/* OPTIONAL - These style changes make the content * wrapper cover the entire comment block. */ .comment { padding: 10px; border: 1px solid black; margin-top: 10px; position:relative; } .comment .content { width:100%; height:100%; position:absolute; top:0; left:0; }
它只取决于你所期望的行为.