动画只工作一次

Animation only works once

我的 javascript 代码有一个小问题。当我点击 .add-case 时,动画功能只工作一次。 'on' 函数中的警报仍然每次都显示。

$(document).on('click', '.add-case', function(){
    height = $('.filling').height(); 
    alert('Works') // This shows every time I click
    $('.filling').animate({ height: $(this).height() + 40}, 600); 
    // this only works once
}); 

有人可以帮忙吗?

问题确实出在 (this) 的使用上。将其更改为 $('.filling') 并且有效。

问题:

这里的问题是被点击元素的 height 在点击时没有改变。因此,每次点击都会检索和更新相同的高度。

$(this).height()

将获得点击元素的高度。 $(this) 事件处理程序内部是发生事件的元素的 jQuery 对象。

解法:

使用相对大小+=40,高度增加40。虽然,$(elementSelector).height() + 40也可以,但最好使用相对单位。

Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

$(document).on('click', '.add-case', function() {
  $('.filling').animate({
    height: '+=40'
  }, 600);
});
.filling {
  height: 10px;
  width: 50%;
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="filling"></div>

<button class="add-case">Click</button>

不要使用 "this",而是尝试通过其 ID 或 class 获取对象。如图所示:

https://jsfiddle.net/HimeshS/y1cqsovg/

 $('.filling').animate({ height: $(".filling").height() + 40}, 600);

如果您正在使用它,它可能会提供文档对象。