我的“停止”按钮不能正常工作。通常情况下,第一次动画继续进行,然后它就开始工作了。我也想知道如何返回div的高度时,停止被点击和显示它。
//HTML
<div id = "wrapper">
<div id = "container">
<div id = "meter"></div>
</div>
<button id ="start">START</button>
<button id ="stop">STOP</button>
</div>
//CSS
#wrapper {
height: 100%; width: 100%;
text-align: center;
}
#container {
height: 300px; width: 60px;
background-color: yellow;
display: block;
margin: 20px auto;
position: relative;
}
#meter {
height: 0;
width: 50px;
position: absolute;
bottom: 0px;
background-color: blue;
margin: 0 5px;
}
button {
width: 75px;
height: 30px;
background-color: red;
border-radius: 15px;
position: relative;
float: left;
display: inline-block;
}
//Javascript
$(document).ready(function() {
$('#start').on('click', function () {
for(var i = 0; i<100; i++) {
$("#meter").animate({height:300}, 1000);
$("#meter").animate({height: 0}, 1000);
$('#stop').on('click', function () {
$("#meter").stop();
});
}
});
});http://jsfiddle.net/2p3xj01j/
发布于 2014-11-15 20:29:53
我可以理解,您希望在#meter上在for-loop中链接200个动画。但是使用您的代码,您还创建了300个jQuery对象,并附加了100倍相同的单击处理程序。您应该从循环中移出一些代码。
创建一个元素,在#容器之前的HTML中显示高度:
<div id = "display">Display height</div>你的JS看起来可能是:
$(document).ready(function() {
var meter = $("#meter"); // create jQuery-object once and store it
$('#start').on('click', function () { // setup for the start-button
// create 200 animations
for(var i = 0; i<100; i++) {
// reference to the variable and chain the jQuery functions
meter.animate({height:300}, 1000).animate({height: 0}, 1000);
}
});
$('#stop').on('click', function () { // setup for the stop-button separate
// stop animations, clear animation queue, get height of meter, get display-element
// set its content to the meter height, and all that with one line
$("#display").html(meter.stop(true).height());
});
});DEMO。
VERSION 2:,而不是链接200个动画,您可以使用complete-callback of .animate()递归调用动画函数,因此它在一个无限循环中运行(当然可以停止,如上面所示):
$(document).ready(function() {
var meter = $("#meter");
function run() { // define a function that runs only two animations
// second animation gets a 'callback' to 'run' so after finishing
// function 'run' is called again
meter.animate({height:300}, 1000).animate({height: 0}, 1000, run);
}
$("#start").click(run); // START calls function 'run'
$('#stop').on('click', function () { // STOP is same as above
$("#display").html(meter.stop(true).height());
});
});有关在.animate() reference中使用回调的详细信息。
https://stackoverflow.com/questions/26949285
复制相似问题