我以为我会编写一个简单的脚本来动画我的网页。
当我按下按钮时,基本的想法是让div变得越来越大。我很好地处理了这个增长的部分,但我不能让它再次收缩。
经过长时间的调试,似乎JavaScript中的减法无法正常工作。基本上,似乎这行不起作用:i = height - 4;
,值i
保持不变。
我包含了一个完整的例子,你能帮我解决一下吗?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<meta http-equiv="Content-Language" content="Estonian" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" />
</head>
<body>
<script type="text/javascript">
var i;
var increasing = new Boolean("true");
var height;
function testFunction() {
height = parseInt(document.getElementById("testDiv").offsetHeight);
if( increasing == true ) {
i = height + 4;
document.getElementById("testDiv").style.height = i + "px";
if( height >= 304 ) {
increasing = false;
}
else {
pause(30);
}
}
else {
i = height - 4;
document.getElementById("testDiv").style.height = i + "px";
if( height <= 104 ) {
increasing = true;
}
else {
pause(30);
}
}
}
function pause(ms) {
setTimeout("testFunction()", ms);
}
</script>
<button id="button" type="button" onclick="testFunction();">Do it!</button.
<div id="testDiv" style="border: 2px solid black; width: 400px; height: 100px; text-align: center;">
Hello!
</div>
</body>
</html>
编辑:标签正在生成HTML,不得不改变&gt;到。
答案 0 :(得分:1)
height = parseInt(document.getElementById("testDiv").offsetHeight);
这可能不是问题,但是在使用parseInt时应始终指定基数。如果字符串以0开头,它将把字符串解释为基数8
parseInt("011") // 9
parseInt("011", 10) // 11
答案 1 :(得分:1)
问题在于,当您执行increasing=false;
时,您不会再次致电pause(30)
。
只需更改您的代码:
if( height >= 304 ) { increasing = false; pause(30); }
这将起作用,我测试了它:)
修改强> 正如dlamblin所说,使用JQuery很容易做到这一点,如果你的目标是动画本身而不是它的“如何”,你应该考虑使用JQuery。
答案 2 :(得分:1)
从您的代码中可以看出,一旦DIV达到最大高度,“increase”就会设置为false,但是你不会再次调用pause(),所以testFunction()实际上永远不会触发“increase”设置为假的。
答案 3 :(得分:0)
说实话,看起来很好,但是学习使用jQuery来实现这一目标会让你获得更好的成绩。 (按下运行)。
答案 4 :(得分:0)
我已经更改了您的代码,这对我来说很好用
替换
height = parseInt(document.getElementById("testDiv").offsetHeight);
与
height = parseInt(document.getElementById("testDiv").style.height , 10);
和
if( height >= 304 ) {
increasing = false;
}
与
if( height >= 304 ) {
increasing = false;
pause(30);
}
if( height <= 104 ) {
increasing = true;
}
与
if( height <= 104 ) {
increasing = true;
pause(30);
}
<强> Working Demo 强>
答案 5 :(得分:0)
您还可以组合IF循环和ELSE循环。用途:
i = height + (increasing) ? 4 : -4;
然后是:
`if(height&lt; 105 || height&gt; 303)增加=!增加;'
这样,如果您更改参数(例如费率),则只需更改一次 --Dave