我有以下代码. id为’selected-plays’的第一个’ul’标签有3个子’li’标签(不是后代).我正在尝试将少量CSS规则应用于这些子标记.
我的jQuery代码添加了“水平”类.请注意,选择器仅指向id为selected-plays的父元素的子标记
$(document).ready(function() { $('#selected-plays > li').addClass('horizontal'); });
.horizontal { margin: 10px; float: left; list-style: none; color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <ul id="selected-plays"> <li>Comedies <ul> <li><a href="/asyoulikeit/">As You Like It</a></li> <li>All's Well That Ends Well</li> <li>A Midsummer Night's Dream</li> <li>Twelfth Night</li> </ul> </li> <li>Tragedies <ul> <li><a href="hamlet.pdf">Hamlet</a></li> <li>Macbeth</li> <li>Romeo and Juliet</li> </ul> </li> <li>Histories <ul> <li>Henry IV (<a href="mailto:henryiv@king.co.uk">email</a>) <ul> <li>Part I</li> <li>Part II</li> www.it-ebooks.info Chapter 2 [ 29 ] </ul> <li><a href="http://www.shakespeare.co.uk/henryv.htm"> Henry V</a></li> <li>Richard II</li> </ul> </li> </ul>
前三个属性(margin,float,list-style)按预期应用于三个子’li’标签,但最后一个属性,即颜色应用于父元素内的所有元素(后代).为什么会这样?
解决方法
这是预期的行为,因为子元素将自动继承其父级的颜色设置.如果您不想要这种行为,可以在CSS中设置子项的颜色:
#selected-plays li li { color: initial; }
$(document).ready(function() { $('#selected-plays > li').addClass('horizontal'); });
.horizontal { margin: 10px; float: left; list-style: none; color: red; } #selected-plays li li { color: initial; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <ul id="selected-plays"> <li>Comedies <ul> <li><a href="/asyoulikeit/">As You Like It</a></li> <li>All's Well That Ends Well</li> <li>A Midsummer Night's Dream</li> <li>Twelfth Night</li> </ul> </li> <li>Tragedies <ul> <li><a href="hamlet.pdf">Hamlet</a></li> <li>Macbeth</li> <li>Romeo and Juliet</li> </ul> </li> <li>Histories <ul> <li>Henry IV (<a href="mailto:henryiv@king.co.uk">email</a>) <ul> <li>Part I</li> <li>Part II</li> www.it-ebooks.info Chapter 2 [ 29 ] </ul> <li><a href="http://www.shakespeare.co.uk/henryv.htm"> Henry V</a></li> <li>Richard II</li> </ul> </li> </ul>