JQuery - 单击时调整div

时间:2017-08-14 08:53:15

标签: jquery

当我点击向下箭头图像时,它会将注释div调整为400px并添加类向上箭头(显示不同的图像)。当我点击向上箭头图像而不是向上320px时,它再次下降320px。我做错了什么?

    $('.arrow-down').click(function() {
            $('.comment').animate({height: '+=320px'}, 1000);   
        $(this).removeClass('arrow-down');
        $(this).addClass('arrow-up');
    });

    $('.arrow-up').click(function() {
            $('.comment').animate({height: '-=320px'}, 1000);   
        $(this).removeClass('arrow-up');
        $(this).addClass('arrow-down');
    });

2 个答案:

答案 0 :(得分:0)

您需要使用委托事件处理程序,因为您在页面加载后更改了元素上的类:



$(document).on('click', '.arrow-down', function() {
  $('.comment').animate({ height: '+=320px' }, 1000);
  $(this).toggleClass('arrow-down arrow-up');
}).on('click', '.arrow-up', function() {
  $('.comment').animate({ height: '-=320px' }, 1000);
  $(this).toggleClass('arrow-down arrow-up');
});

.comment {
  padding: 5px;
  border: 1px solid #CCC;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment">This is a comment...</div>
<div class="arrow-down">Click me</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

希望这有助于你

$(document).on('click', '.arrow-down', function(event) {
    $('.comment').animate({height: '+=320px'}, 1000);
    $(this).removeClass('arrow-down');
    $(this).addClass('arrow-up');
});
$(document).on('click', '.arrow-up', function(event) {
    $('.comment').animate({height: '-=320px'}, 1000);
    $(this).removeClass('arrow-up');
    $(this).addClass('arrow-down');
});