我正在尝试在css中设置以下动画。我已经阅读了以前的帖子,但settimeout
似乎没有起作用,或者它似乎没有给我预期的结果。
我正在尝试做一个简单的动画,每次更改行高0.5,我已经尝试了一个循环,我尝试了手动,但都没有效果。它只是向我显示“最终”结果,然后如果我按下按钮,甚至不会改变任何东西。这是一个例子:
$(document).ready(function() {
$("#linespace001").click(function() {
var crap = 0;
// this for some stupid reason DOESNT work
for (i = 1; i <= 3; i++) {
crap += 1000;
setTimeout(function() {
$("#poop").css("line-height", i * 0.5);
}, crap);
// this for some stupid reason works
setTimeout(function() {
$("#poop").css("line-height", 0.5);
}, 1000);
setTimeout(function() {
$("#poop").css("line-height", 1);
}, 2000);
setTimeout(function() {
$("#poop").css("line-height", 1.5);
}, 3000);
}
});
});
<input type=button id=linespace001 value="Animate button!">
<div id="poop">
This is a sample test/changing the line height/spacing
<br>This is a sample test/changing the line height/spacing
<br>This is a sample test/changing the line height/spacing
<br>This is a sample test/changing the line height/spacing
<br>This is a sample test/changing the line height/spacing
<br>This is a sample test/changing the line height/spacing
<br>
</div>
答案 0 :(得分:1)
而不是setTimeout()
使用setInterval()
$(function() {
var i = 1,
lineHeight = 0.5;
$("#linespace001").on("click", function() {
var heightTimer = setInterval(function() {
if (i > 3) {
clearInterval(heightTimer);
i = 1;
return false;
}
$("#poop").css({"line-height" : (i * lineHeight)});
i++;
}, 500);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="linespace001" value="Animate button!">
<div id="poop">
This is a sample test/changing the line height/spacing<br>
This is a sample test/changing the line height/spacing<br>
This is a sample test/changing the line height/spacing<br>
This is a sample test/changing the line height/spacing<br>
This is a sample test/changing the line height/spacing<br>
This is a sample test/changing the line height/spacing<br>
</div>