1.思考:页面上有一个宽高都为100px的盒子,如果想点击此盒子,让它的宽变成300px,应该怎么做 ?思路一:选择用js的点击事件做,给盒子添加类名,并在类名中写对应的css样式。<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> #box{ width: 100px; height: 100px; background: red; transition: 1s; } #box.c{ width: 300px; } </style></head><body> <div id="box"></div> <script> var box=document.getElementById("box"); console.log(box); box.onclick=function () { console.log(1); this.className="c"; } </script></body></html>思路二:使用定时器做,让盒子的宽度每20毫秒加5px。直到盒子的宽度大于或着等于300px。<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> #box{ width: 100px; height: 100px; background: red; } </style></head><body> <div id="box"></div> <script> var box=document.getElementById("box"); box.onclick=function () { var num=5; var w=parseFloat(getComputedStyle(box).width); var timer=setInterval(function () { w+=5; if(w>=300){ clearInterval(timer); w=300 } box.style.width=w+"px"; },20) } </script></body></html>将思路二封装成函数,使的每个元素都可以使用。例如还改变盒子的高度值,可以改变传入的参数值。<script> var box=document.getElementById("box"); //Element:页面中哪个元素 //attr:元素的哪个属性 //step:每个周期改变多少 //target:元素的目标值 function move(element,attr,step,target) { var now=parseFloat(getComputedStyle(element)[attr]); var timer=setInterval(function () { now+=step; if(now>=target){ clearInterval(timer); now=target } element.style[attr]=now+"px"; },20) } box.onclick=function () { move(box,"width",5,300); }</script>2.有时候需要在规定时间完成宽的变大或者变小。例如需要在2秒完成,盒子从宽100px到0<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> #box{ width: 100px; height: 100px; background: red; } </style></head><body><div id="box"></div><script> var box=document.getElementById("box"); //Element:页面中哪个元素 //attr:元素的哪个属性 //target:元素的目标值 //duration:持续时间 function move(element,attr,target,duration) { var star=parseFloat(getComputedStyle(element)[attr]);//起点 var c=target-star;//c表示总路程 var t=duration;//所需时间 var starTime=new Date().getTime();//开始时间 var timer=setInterval(function () { var nowTime=new Date().getTime();//现在时间 var takeTime=nowTime-starTime;//花费时间 if(takeTime>=t){ clearInterval(timer); takeTime=t; } var now=c/t*takeTime+star;//路程/时间*已花费时间+原本宽度=那一刻的宽度(跟路程公式一样) element.style[attr]=now+"px"; },20) } box.onclick=function () { move(box,"width",0,5000); }</script></body></html>
