我想使用setInterval函数在JavaScript中创建动画,但我遇到了问题。
我用过:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.main{
width:80%;
margin:auot;
text-align: center;
}
p{
position:absolute;
top:0px;
}
</style>
</head>
<body>
<div class="main">
<h1>bianti</h1>
</div>
<p id="mydiv">ssss</p>
<script type="text/javascript" >
var obj=document.getElementById('mydiv');
function changeStyle(){
obj.style.top=parseInt(obj.style.top)+200+'px'
}
setInterval(changeStyle,1000);
</script>
</body>
</html>
但它不起作用。我使用内联css更换代码并替换嵌入式css。然后它有效,但我不知道为什么。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.main{
width:80%;
margin:auot;
text-align: center;
}
</style>
</head>
<body>
<div class="main">
<h1>bianti</h1>
</div>
<p id="mydiv" style="position:absolute;top:0;">ssss</p>
<script type="text/javascript" >
var obj=document.getElementById('mydiv');
function changeStyle(){
obj.style.top=parseInt(obj.style.top)+200+'px'
}
setInterval(changeStyle,1000);
</script>
</body>
</html>
答案 0 :(得分:5)
回答这个问题:
但它不起作用
由于style.top
为空,parseInt
未返回整数值。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.main {
width: 80%;
margin: auot;
text-align: center;
}
p {
position: absolute;
top: 0px;
}
</style>
</head>
<body>
<div class="main">
<h1>bianti</h1>
</div>
<p id="mydiv">ssss</p>
<script type="text/javascript">
var obj = document.getElementById('mydiv');
function changeStyle() {
var init = 0;
if (obj.style.top) {
init = parseInt(obj.style.top);
}
obj.style.top = init + 200 + 'px'
}
setInterval(changeStyle, 1000);
</script>
</body>
</html>
答案 1 :(得分:0)
这会有效。在你的CSS中让#mydiv {...}
var obj=document.querySelector('#mydiv');
function changeStyle(){
obj.style.top+= "200px";
}
setInterval(changeStyle,1000);
答案 2 :(得分:-1)