原生js实现图片放大缩小计时器效果
知识要点
varfn=setInterval(function(){},1000)
每隔1秒执行一次函数
clearInterval(fn)
清除计时器
判断当图片放大缩小到固定大小时,清除计时器
完整代码
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>demo</title>
<style>
body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt,dd,ul,ol,li,pre,form,fieldset,legend,button,input,textarea,th,td{margin:0;padding:0;}
body,button,input,select,textarea{font:12px/1.5tahoma,arial,\5b8b\4f53;}
h1,h2,h3,h4,h5,h6{font-size:100%;}
address,cite,dfn,em,var{font-style:normal;}
code,kbd,pre,samp{font-family:couriernew,courier,monospace;}
small{font-size:12px;}
ul,ol{list-style:none;}
a{text-decoration:none;}
a:hover{text-decoration:underline;}
sup{vertical-align:text-top;}
sub{vertical-align:text-bottom;}
legend{color:#000;}
fieldset,img{border:0;}
button,input,select,textarea{font-size:100%;}
table{border-collapse:collapse;border-spacing:0;}
.clear{clear:both;float:none;height:0;overflow:hidden;}
</style>
</head>
<body>
<divstyle="width:400px;margin:0auto;">
<imgsrc="http://img.mukewang.com/53577ee900016c2102080260.jpg"id="myImage"/><br>
<inputtype="button"id="max"value="放大"/>
<inputtype="button"id="min"value="缩小"/>
</div>
<scripttype="text/javascript">
functionpic_max(){
varmaxBtn=document.getElementById("max");
varminBtn=document.getElementById("min");
maxBtn.onclick=function(){
max();
}
varimg=document.getElementById("myImage");
varmaxHeight=img.height*2;
varmaxWidth=img.width*2;
functionmax(){
varendHeight=img.height*1.3;
varendWidth=img.width*1.3;
varmaxTime=setInterval(function(){
if(img.height<endHeight&&img.width<endWidth){
if(img.height<maxHeight&&img.width<maxWidth){
img.height=img.height*1.05;
img.width=img.width*1.05;
}else{
alert("图片已经是最大值了")
clearInterval(maxTime);
}
}else{
clearInterval(maxTime);
}
},20);
}
minBtn.onclick=function(){
min();
}
varimg=document.getElementById("myImage");
varminHeight=img.height*0.5;
varminWidth=img.width*0.5;
functionmin(){
varoverHeight=img.height*0.7;
varoverWidth=img.width*0.7;
varminTime=setInterval(function(){
if(img.height>overHeight&&img.width>overWidth){
if(img.height>minHeight&&img.width>minWidth){
img.height=img.height*0.95;
img.width=img.width*0.95;
}else{
alert("图片已经是最小值了")
clearInterval(minTime);
}
}else{
clearInterval(minTime);
}
},20);
}
}
window.onload=function(){
pic_max();
}
</script>
</body>
</html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!