选择过滤器(一个/两个/三个(后,如何保留CSS奇数/偶数项?
在CSS中,我说.grid .show:nth-of-type(odd){filter:sepia(100%);}
但当我选择一个过滤器时,顺序是不正确的。这一定很简单。
你可以在我的演示中看到这里。当我选择一个按钮时,它需要是奇数/偶数,但它没有。https://jsfiddle.net/fourroses666/otda1bec/3/
:nth-of-type
选择特定类型的nth子级,但它不关心类。如果你想让它持续工作,你可能想从列表中添加和删除项目以保持CSS的正确性,我建议如下(注意,我已经尝试删除了任何分散注意力的元素,不需要所有的类名和样式,所以我简化了它以保持重点:
const wrapper = document.querySelector( '.grid' );
const filterables = Array.from( wrapper.children );
function filter(c) {
filterables.forEach(item => {
if( c === 'all' || item.classList.contains( c ) ){
wrapper.appendChild( item );
} else {
item.remove();
}
});
}
.grid {
margin:0 0 50px;
transition: height .2s;
display:flex;
flex-wrap:wrap;
}
.grid:after {
content: '';
display: block;
clear: both;
}
.grid > * {
display: block;
filter: grayscale(0%);
position: relative;
margin: 0;
min-width: 20%;
max-width: 20%;
width: 20%;
transition: all .3s ease-in-out;
height: 0;
padding-top: 20%;
background-image: url(http://placekitten.com/g/601/601);
background-color: var(--color2);
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.grid > *:hover {
filter:grayscale(100%);
}
.grid > * h3 {
position: absolute;
top: 40%;
left: 10px;
text-align: center;
width: 50%;
background: white;
}
.grid > *:nth-child(odd) {
filter: invert(100%);
}
<div id="filter-box">
<button class="btn all" onclick="filter('all')">all</button>
<button class="btn one" onclick="filter('one')">one</button>
<button class="btn two" onclick="filter('two')">two</button>
<button class="btn three" onclick="filter('three')">three</button>
</div>
<br>
<div class="grid">
<div class="one"><h3>one</h3></div>
<div class="three"><h3>three</h3></div>
<div class="three"><h3>three</h3></div>
<div class="one"><h3>one</h3></div>
<div class="two"><h3>two</h3></div>
<div class="one"><h3>one</h3></div>
<div class="one"><h3>one</h3></div>
<div class="two"><h3>two</h3></div>
<div class="three"><h3>three</h3></div>
<div class="two" ><h3>two</h3></div>
<div class="two"><h3>two</h3></div>
<div class="one"><h3>one</h3></div>
</div>
您可能还注意到,我高度简化了您的filter
函数(您使它变得有点不必要的复杂(。这个过滤器只是检查元素上是否存在className(使用classList.contains()
,请参见下文(,然后从页面流中添加或删除该元素。
关于这一点,我还想补充一点,在未来,不要编写自己的AddClass
和RemoveClass
方法。相反,使用classList
在任何已经解决的边缘情况下始终为您做到这一点:
htmlElement.classList.add( 'show' )
htmlElement.classList.remove( 'show' )
htmlElement.classList.toggle( 'show', optionalBooleanCheckToToggleAppropriately )
这些方法更加稳健。
您可以直接使用第n个子项,而不是类型的第n个子
.grid.show:nh child(奇数({filter:sepia(100%(;}