day08运动函数封装
1.回顾
2.同步异步
-
同步:在做一件事的时候,如果这件事没有做完,后面的代码只能等待
-
for alert是同步
-
-
异步:在做一件事的时候,如果这件事需要等待,先去执行后面的代码,等时间到了再回来执行代码
-
定时器 ajax promise 事件绑定都是异步
-
<body> <script> // 同步 for (var i = 0; i < 100000; i++) { console.log(i); } console.log("结束了吗"); alert("提示信息")//阻塞性弹窗 console.log(2); //异步 console.log("开始"); setTimeout(function () { console.log(1); }, 0) console.log("结束"); // //事件绑定 console.log(1) btn.onclick = function () { console.log("3"); } console.log(2); </script>
3.小鸟起飞
3.1开始飞
-
需求:点击开始飞按钮 小鸟往右飞,飞到1000px的位置停止
-
==问题1:点击开始起飞 越点小鸟飞的越快==
-
分析:定时器累加的问题
-
解决:每次声明定时器之前 先清除原先的定时器
-
<body> <button>开始飞</button> <br> <img src="./img/right.gif" alt=""> <script> /* 问题1:点击开始起飞 越点越快 分析:定时器累加的问题 解决:每次声明定时器之前 先清除原先的定时器 */ var btn = document.getElementsByTagName("button"); var oImg = document.getElementsByTagName("img")[0]; var timer; //1.点击开始起飞 btn[0].onclick = function () { //建议:但凡是牵扯到元素移动的 建议使用定义偏移量(left right bottom top); //4.清除定时器 clearInterval(timer); //2.添加定时器 timer = setInterval(function () { //想在left值的基础上+10 如何获取left值 var current = parseInt(getStyle(oImg, "left")) + 10;//当前的left值 //3.运动到1000px停止 if (current >= 1000) { current = 1000; //清除定时器 clearInterval(timer); } oImg.style.left = current + "px"; }, 50) } </script> </body>
3.2来回飞
-
需求:点击凯旋按钮,小鸟往回飞
-
==问题2:点击凯旋的时候,越点小鸟飞的越快==
-
分析:定时器累加的问题
-
解决:在每次声明定时器的时候,都将原先的定时器清除
-
<body> <button>开始飞</button> <button>凯旋</button> <br> <img src="./img/right.gif" alt=""> <script> var btn = document.getElementsByTagName("button"); var oImg = document.getElementsByTagName("img")[0]; var timer; //1.点击开始起飞 btn[0].onclick = function () { //改变图片的路径 oImg.src = "./img/right.gif"; //4.清除定时器 clearInterval(timer); //2.添加定时器 timer = setInterval(function () { //想在left值的基础上+10 如何获取left值 var current = parseInt(getStyle(oImg, "left")) + 10;//当前的left值 //3.运动到1000px停止 if (current >= 1000) { current = 1000; //清除定时器 clearInterval(timer); } oImg.style.left = current + "px"; }, 50) } /* 问题2:点击凯旋的时候,越点小鸟飞的越开 分析:定时器累加的问题 解决:在每次声明定时器的时候,都将原先的定时器清除 */ // 5.凯旋 btn[1].onclick = function () { //改变图片的路径 oImg.src = "./img/left.gif"; // 8.清除定时器 clearInterval(timer); //6.添加定时器 timer = setInterval(function () { // 在当前left值的基础上-10 var current = parseInt(getStyle(oImg, "left")) - 10;//当前left值 // 7.运动到0px停止 if (current <= 0) { current = 0; clearInterval(timer); } oImg.style.left = current + "px"; }, 50) } </script>