图片居中按比例显示、鼠标滚动缩放、鼠标拖动平移
1.为了居中显示,考虑到div不好设置,用table做边框
缩放原理:调整图片宽高、定位left、top;
平移:鼠标事件位置、定位left、top。
目前贴出实现代码,具体研究内容再做补充
下面是源码
<!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></title> <script src='/js/jquery-1.7.2.min.js' type='text/javascript'></script> <style> html,body { margin:0; height:100%; }
//图片绝对定位,平移时使用 #box { position:absolute; } </style> </head> <body> <table style="height:100%;width:100%;" id="tabID" > <tr > <td style="text-align:center;vertical-align:middle;"> <img src="/images/a.png" id="box" onload="AutoResizeImage(800,600,this)" onmousewheel="return bbimg(this)" /> </td> </tr> </table> <script type="text/javascript"> // img缩放 --> function bbimg(o){
//下面3行代码也可以缩放,但是跟position:absolute冲突,会导致图片的left、top定死,只能往右往下缩放
// var zoom=parseInt(o.style.zoom, 10)||100;
// zoom+=event.wheelDelta/12;
//if (zoom>0) o.style.zoom=zoom+'%';
var w=o.width;
var h=o.height;
if(event.wheelDelta>0){//放大 wheelDelta大于0是滚轮往下,小于滚轮往上
o.width=w*1.3;
o.height=h*1.3;
var left=o.offsetLeft;
var top=o.offsetTop;
o.style.left=left-(0.3 * w)/2+"px";
o.style.top=top-(0.3 * h)/2+"px";
}else{
o.width=w*0.7;
o.height=h*0.7;
var left=o.offsetLeft;
var top=o.offsetTop;
o.style.left=left+(0.3 * w)/2+"px";
o.style.top=top+(0.3 * h)/2+"px";
}
return false;
}
//初始设置图片显示、位置
function AutoResizeImage(maxWidth,maxHeight,objImg){
var img = new Image();
img.src = objImg.src;
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth ==0 && maxHeight==0){
Ratio = 1;
}else if (maxWidth==0){
if (hRatio<1) Ratio = hRatio;
}else if (maxHeight==0){
if (wRatio<1) Ratio = wRatio;
}else if (wRatio<1 || hRatio<1){
Ratio = (wRatio<=hRatio?wRatio:hRatio);
} if (Ratio<1){
w = w * Ratio;
h = h * Ratio;
}
objImg.height = h;
objImg.width = w;
objImg.style.left=(maxWidth-w)/2+"px";
objImg.style.top=(maxHeight-h)/2+"px";
}
//拖动
var oDiv = document.getElementById("box");
oDiv.onmousedown=function(ev) {
var oEvent = ev||event;
var disX = oEvent.clientX - oDiv.offsetLeft;
var disY = oEvent.clientY - oDiv.offsetTop;
document.onmousemove=function (ev) {
oEvent = ev||event; //360兼容模式不识别ev,故拼上event
oDiv.style.left = oEvent.clientX -disX+"px";
oDiv.style.top = oEvent.clientY -disY+"px";
return false;
}
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
}
return false;
}
</script>
</body>
</html>