一般来说,实现图片的放大缩小功能都用到了比较大的封装插件,特别是以jQuery插件居多,而实际上单纯实现对原图本身的放大缩小,用简单几行原生JS代码就可以做到。在今天分享的这个实例中,点击放大按钮不松鼠标,图片会不断的逐渐放大,当然也可以点一下放大一点,点击缩小按钮则反之,有需要的朋友可以考虑收藏备用哦
以下为全部代码:
<html><head>
<meta http-equiv="Content-Type" content="text/html charset=utf-8" />
<title>javascript控制图片缩小或者放大</title>
</head>
<body>
<script type="text/javascript">
var oTime
function changeSize(id,action){
var obj=document.getElementById(id)
obj.style.zoom=parseInt(obj.style.zoom)+(action=='+'?+10:-10)+'%'
oTime=window.setTimeout('changeSize(\''+id+'\',\''+action+'\')',100)
}
document.onmouseup=function(){
window.clearTimeout(oTime)
}
</script>
<div style="height:350px overflow: auto">
<img id="headImg" src="
<button onmousedown="changeSize('headImg','+')" onmouseup="window.clearTimeout(oTime)">放大</button>
<button onmousedown="changeSize('headImg','-')" onmouseup="window.clearTimeout(oTime)">缩小</button>
</body>
</html>
用js控制图片额大小。主要是修改图片的宽度和高度。下面是简单的代码实现:
HTML 代码:
<img src='../1.jgp' id='img' />这个时候img的图片自身是多大,就会显示多大。100px*100px的图。
js代码:
var oImg = document.getElementById('img')oImg.width = '50px' //当给img标签的宽度设置为50px后,高度会自动按比例缩小。
oImg.width = '200px' //当给img标签的宽度设置为200px后,高度会自动按比例扩大。
图片按比例缩放function DrawImage(Img,WIDTH,HEIGHT){
var image=new Image()
image.src=Img.src
width=WIDTH//预先设置的所期望的宽的值
height=HEIGHT//预先设置的所期望的高的值
if(image.width>width||image.height>height){//现有图片只有宽或高超了预设值就进行js控制
w=image.width/width
h=image.height/height
if(w>h){//比值比较大==>宽比高大
//定下宽度为width的宽度
Img.width=width
//以下为计算高度
Img.height=image.height/w
}else{//高比宽大
//定下宽度为height高度
img.height=height
//以下为计算高度
Img.width=image.width/h
}
}
}
<img src="xxxx" onload=javascript:DrawImage(this,290,215)>