【发布时间】:2015-11-29 21:19:22
【问题描述】:
我有一组按网格排列的 div。
要设置每个 div 的样式,我使用 nth-child() pseudo-class 选择它们。
div.tile:nth-child(4n-7) .text { background-color: yellow; }
用户可以通过单击按钮来隐藏 div(该按钮会触发一个 jQuery 函数,该函数将 display: none 规则添加到所选 div 中的 class 属性)。
jQuery
$('.hide-divs').click(function () {
$('.dolphin').toggleClass('hidden');
})
CSS
.hidden { display: none; }
问题来了:
即使display: none 从屏幕中删除了 div,它并没有从 DOM 中删除 div,所以 nth-child 选择器在应用样式时仍然会计算它,这反过来又会打乱网格的视觉设计.
上面的布局被破坏了,因为只有第一列应该是黄色的。
所以我的第一个想法是使用 jQuery remove() method,它将元素(及其后代)从 DOM 中取出。
但事实证明,一旦应用了remove(),您就无法取回这些 div。他们走了。所以切换功能中断。
经过一番研究,我发现了 jQuery detach() method,它与 .remove() 做同样的事情,除了它存储删除元素的数据以供以后使用。
.detach()方法与.remove()相同,不同之处在于.detach()保留所有与已删除关联的 jQuery 数据 元素。当要移除元素时,此方法很有用 稍后重新插入到 DOM 中。
detach() 与拨动开关一起工作看起来一切都很好,除了我实现它的努力没有奏效。
我使用example on the jQuery website 作为指南,但它在网格上不起作用。我还阅读了该网站上的各种相关帖子,但无济于事。我一定是错过了什么。
任何反馈将不胜感激。
$('.hide-divs').click(function() {
$('.dolphin').toggleClass('hidden');
})
.row {
display: flex;
flex-wrap: wrap;
width: 500px;
padding: 0;
margin: 0;
}
.text {
height: 50px;
width: 100px;
margin: 10px;
padding-top: 15px;
background: tomato;
color: #fff;
text-align: center;
font-size: 2em;
}
.tile:nth-child(4n-7) .text {
border: 2px solid #ccc;
background-color: yellow;
color: #000;
}
button {
padding: 10px;
background-color: lightblue;
position: relative;
left: 200px;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="tile">
<div class="text">01</div>
</div>
<div class="tile">
<div class="text">02</div>
</div>
<div class="tile">
<div class="text dolphin">03</div>
</div>
<div class="tile">
<div class="text">04</div>
</div>
<div class="tile">
<div class="text">05</div>
</div>
<div class="tile">
<div class="text dolphin">06</div>
</div>
<div class="tile">
<div class="text">07</div>
</div>
<div class="tile">
<div class="text dolphin">08</div>
</div>
<div class="tile">
<div class="text">09</div>
</div>
<div class="tile">
<div class="text">10</div>
</div>
<div class="tile">
<div class="text">11</div>
</div>
<div class="tile">
<div class="text">12</div>
</div>
</div><!-- end .row -->
<button type="button" class="hide-divs">HIDE DIVS 3, 6 & 8</button>
【问题讨论】:
标签: javascript jquery html css