在列表项中添加/删除类

Adding / Removing classes to list items

本文关键字:删除 添加 列表      更新时间:2023-09-26

所以我已经建立了这个带有左右导航箭头的小滑块,我在尝试向ul中的列表项添加类时遇到了麻烦。

基本上,我想在列表的下一项中添加一个类,同时从前一项中删除该类。

现在的问题是,我已经使这个工作完美,但只是在正确的方向,而不是左边。

请注意,列表项在两个方向上都能正确排序,它只是在左边添加了一个类,而不是:

$('.home_slider > li:first').addClass('active-slide');
$('#slider_arrow_right').click(function(){
  $('.active-slide').next().addClass('active-slide').prev().removeClass('active-slide');
  $('.home_slider > li:last').after($('.home_slider > li:first'));
});
$('#slider_arrow_left').click(function(){
  $('.home_slider > li:first').before($('.home_slider > li:last'));
  $('.active-slide').next().addClass('active-slide').prev().removeClass('active-slide');      
});

我已经尝试改变#slider_arrow_left click函数在几个不同的方式,但它仍然添加类在相同的列表方向为右箭头,或者只是不工作。任何帮助都非常感激!

更新:

下面是一个显示问题的JSFiddle:

使用css子选择器。它将使你的生活在这个用例中更容易,并减少你的代码。

JavaScript

$('#right').click(function(){
  $('.home_slider > li:last').after($('.home_slider > li:first'));
});
$('#left').click(function(){
  $('.home_slider > li:first').before($('.home_slider > li:last')); 
});
CSS

.nav_buttons{
  display:inline-flex;
  color:#fff;
  padding:16px;
}
#left{
  width:40px;
  height:40px;
  margin-right:8px;
  background:grey;
  padding:4px;
}
#right{
  width:40px;
  height:40px;
  background:grey;
  padding:4px;
}
.home_slider{
  display:inline-flex;
  list-style-type:none;
}
.home_slider li{
  width:80px;
  height:80px;
}
#one{
  background:blue;
}
#two{
  background:red;
}
#three{
  background:yellow;
}
#four{
  background:green;
}
.home_slider>li:first-child{
   border:8px solid black;
}

如果你需要得到第一个子元素,如果它在后面的代码中有任何意义。

var firstChild = $('.home_slider li:first-child');

要做动画,只需改变css。

添加到css

@keyframes FadeIn { 
  from { opacity: 0; }
  to   { opacity: 1; }
}

并将它添加到已经存在的子选择器中。

animation: FadeIn 1s linear;