JS如何使列表项滑动

时间:2017-06-27 00:41:00

标签: javascript jquery html

我需要制作一个可伸缩的菜单,当用户触摸它应该在屏幕上滑动的项目时,但是在我的代码中,当项目被播放时,列表中的所有其他项目也会滑动。我只需要触摸的项目在屏幕上滑动。

我的HTML代码:

<ul id="menu-mobile">
        <li class="li-mobile hospital"><i class="fa fa-plus fa-2x" aria-hidden="true"></i>Hospital</li>
        <li class="li-mobile especialidades"><i class="fa fa-star-o fa-2x" aria-hidden="true"></i>Especialidades</li>
        <li class="li-mobile exames"><i class="fa fa-stethoscope fa-2x" aria-hidden="true"></i>Exames</li>
        <li class="li-mobile blog">Blog</li>
        <li class="li-mobile contato"><i class="fa fa-envelope-o fa-2x" aria-hidden="true"></i>Contato</li>
        <li class="li-mobile emergencia">Emergência</li>
    </ul>  



$(".li-mobile").click(function(e){
        if($(this).hasClass("toggle")) {
           $(this).removeClass('toggle').siblings().removeClass('toggle');
        }else{
            $(this).addClass('toggle').siblings().removeClass('toggle');
        }
    });

TKS。

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$(".li-mobile").click(function(e) {
  $(this).siblings().removeClass('toggle');

  if ($(this).hasClass("toggle")) {
     $(this).removeClass('toggle');
  } else {
     $(this).addClass('toggle');
  }
});
&#13;
#menu-mobile {
  right: 0;
  overflow: hidden;
  z-index: 999;
  position: absolute;
  width: 200px;
}

.li-mobile.hospital {
  background-color: #EEF463;
}

.li-mobile.especialidades {
  background-color: #E8B281;
}

.li-mobile.exames {
  background-color: #A2C8CA;
}

.li-mobile.blog {
  background-color: #CE737F;
}

.li-mobile.contato {
  background-color: #007969;
}

.li-mobile.emergencia {
  background-color: #CC2C69;
}

.li-mobile {
  position: relative;
  height: 40px;
  right: -180px;
  list-style-type: none;
  color: #fff;
  width: 100%;
  font-size: 14px;
  -webkit-transition: all 1s ease-in-out;
  -moz-transition: all 1s ease-in-out;
  -o-transition: all 1s ease-in-out;
  transition: all 1s ease-in-out;
}

.li-mobile.toggle {
  right: 40px;
  margin-left: 66px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id="menu-mobile">
  <li class="li-mobile"><i class="fa fa-plus fa-2x" aria-hidden="true"></i>Hospital</li>
  <li class="li-mobile especialidades"><i class="fa fa-star-o fa-2x" aria-hidden="true"></i>Especialidades</li>
  <li class="li-mobile exames"><i class="fa fa-stethoscope fa-2x" aria-hidden="true"></i>Exames</li>
  <li class="li-mobile blog">Blog</li>
  <li class="li-mobile contato"><i class="fa fa-envelope-o fa-2x" aria-hidden="true"></i>Contato</li>
  <li class="li-mobile emergencia">Emergência</li>
</ul>
&#13;
&#13;
&#13;

所有li一起移动的原因是因为ul position: fixed。那应该是absolute,而li应该是relative,因为它们可以独立于ul移动。