Jquery 切换一个 div 动画,同时改变一个类名

标签 jquery html css toggle

首先感谢关注, 我为此目的使用 jquery `当我点击 $('.icon') 时,它必须做两件事,首先将 $('.thediv') 动画化到 {top: of '90px and back 0px'},第二个改变 $('.icon') 类以获得人字形向上并返回人字形向下的东西, 我不明白我做对了什么; 这是 fiddle

var fltro = function(){
	var t = 200;
	$('.filter-tog .fa').click(function(){
		$('.filter').animate({top: '70px'}, t);
		$('.filter-tog .fa').removeClass('fa-chevron-down').addClass('fa-chevron-up');
	});
  $('.filter-tog .fa').click(function(){
		$('.filter').animate({top: '20px'}, t);
		$('.filter-tog .fa').removeClass('fa-chevron-up').addClass('fa-chevron-down');
	});
};
$(document).ready(fltro);
.header{
  height:50px;
  width:300px;
  background-color:red;
}
.filter{
	width: 300px;
    height: 40px;
    position: absolute;
    top: 20px;
    background-color: rgb(16, 160, 122);
    z-index: -4;
}
.filter-tog{
	 width: 20px;
    height: 15px;
    color: white;
    background-color: rgb(27, 77, 88);
    position: absolute;
    top: 8px;
    left: 308px;
    z-index: 8;
}
.filter-tog i{
	line-height: 15px;
    font-size: 15px;
    text-align: center;
    color: white;
    float: none;
    margin: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
</div>
<div class="filter-tog">
	<i class="fa fa-chevron-down"></i>
</div>
<div class="filter">
</div>

最佳答案

只需使用一个变量来跟踪切换条件的状态:

var t = 200, st = 0;
$('.filter-tog .fa').click(function() {
    if (st==0){
        $('.filter').animate({
            top: '70px'
        }, t);
        $('.filter-tog .fa').switchClass('fa-chevron-down', 'fa-chevron-up');
        st++;
    }else{
        $('.filter').animate({
            top: '20px'
        }, t);
        $('.filter-tog .fa').switchClass('fa-chevron-up', 'fa-chevron-down');
        st = 0;
    }
});

jsFiddle Demo

关于Jquery 切换一个 div 动画,同时改变一个类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802124/

相关文章:

javascript - 如何获取:contains() Selector using an Array with multiple matches in a DIV?的总实例

javascript - 数组中的 div 距窗口顶部的距离

javascript - 当用户从上向下滚动时滚动到元素

javascript - 无法隐藏 <em>-Element,它在 Javascript 中作为 String 添加; textContent 不隐藏

jQuery 自定义内容滚动条动画

javascript - 没有页面滚动条的响应式 Bootstrap 模式

html - 背景附件:已修复,在 Chrome 版本之间移动位置

javascript - 更改 :hover CSS properties with JavaScript

html - 如何修复溢出其容器的图像?

javascript - 实时搜索中没有列出隐藏的部分?