欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

原生js实现图片放大缩小计时器效果

程序员文章站 2023-11-03 13:55:27
知识要点 var fn=setinterval(function(){},1000) 每隔1秒执行一次函数 clearinterval(fn) 清除计时器 判断当...

知识要点

var fn=setinterval(function(){},1000)

每隔1秒执行一次函数

clearinterval(fn)

清除计时器

判断当图片放大缩小到固定大小时,清除计时器

完整代码

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-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.5 tahoma,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:courier new,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>
<div style="width:400px;margin:0 auto;">
 <img src="http://img.mukewang.com/53577ee900016c2102080260.jpg" id="myimage" /><br>
 <input type="button" id="max" value="放大" />
 <input type="button" id="min" value="缩小" />
</div>
<script type="text/javascript">
function pic_max(){
 var maxbtn=document.getelementbyid("max");
 var minbtn=document.getelementbyid("min"); 
 maxbtn.onclick=function(){
 max();
 }
 var img=document.getelementbyid("myimage");
 var maxheight=img.height*2;
 var maxwidth=img.width*2;
 function max(){
 var endheight=img.height*1.3;
 var endwidth=img.width*1.3;
 var maxtime=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();
 }
 var img=document.getelementbyid("myimage");
 var minheight=img.height*0.5;
 var minwidth=img.width*0.5;
 function min(){
 var overheight=img.height*0.7;
 var overwidth=img.width*0.7;
 var mintime=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> 

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!