【发布时间】:2023-03-14 18:17:02
【问题描述】:
我试图根据我向下滚动页面的程度沿 y 方向的大 div 移动一个小 div。但我发现使用 setTimeout() 和 setInterval() 会产生两个完全不同的结果。实际上setInterval()被浏览器挂了好几次。这两个函数的基本区别是什么??
<!DOCTYPE html>
<head>
<title>creat a dynamic div</title>
<style>
#mydiv{
border:2px solid green;
}
</style>
</head>
<body>
<script>
var i=0;
var elem1=document.createElement("div");
var atts1=document.createAttribute("style");
atts1.value="width:200px;height:3200px;border:1px solid black;background-color:orange;";
elem1.setAttributeNode(atts1);
document.body.appendChild(elem1);
var elem2=document.createElement("div");
var atts2=document.createAttribute("style");
var atts22=document.createAttribute("id");
atts22.value="mydiv";
atts2.value="width:200px;height:300px;background-color:red;position:absolute;top:0px;left:300px;";
elem2.setAttributeNode(atts2);
elem2.setAttributeNode(atts22);
document.body.appendChild(elem2);
function moveIt(){
var a=window.pageYOffset;
if(i > (a+30)){
clearTimeout(p);
}else{
elem2.style.top=i+"px";
i=i+1;
}
var p=setTimeout(moveIt,200);
}
window.onscroll=moveIt;
</script>
</body>
<html>
【问题讨论】:
-
当然,它们给出完全不同的结果。它们是完全不同的功能。快速查看文档、快速搜索或快速测试将清楚区别。
标签: javascript