Fix a zoom in and out coding

2019-06-12 13:09发布

问题:

I am using the following coding

<html>
 <head>
  <style>
     #thediv {
     margin:0 auto;
     height:400px;
     width:400px;
     overflow:hidden;
   }
   img {
     position: relative;
     left: 50%;
     top: 50%;
   }
  </style>
 </head>
 <body>
  <input type="button" value ="-" onclick="zoom(0.9)"/>
  <input type="button" value ="+" onclick="zoom(1.1)"/>
  <div id="thediv">
    <img id="pic" src="http://upload.wikimedia.org/wikipedia/commons/d/de/Nokota_Horses_cropped.jpg"/>
  </div>

 <script>
  window.onload = function(){
    zoom(1)
  }
  function zoom(zm) {
    img=document.getElementById("pic")
    wid=img.width
    ht=img.height
    img.style.width=(wid*zm)+"px"
    img.style.height=(ht*zm)+"px"
    img.style.marginLeft = -(img.width/2) + "px";
    img.style.marginTop = -(img.height/2) + "px";
  }
  </script>
 </body>
</html>

For making a simple zoom in and zoom out function.

I this i have a difficulty of the image is zooming indefinitely. i want to fix a position to zoom in and zoom out. The image must not exceed that position while zooming in and zooming out.

I am adding a fiddle to this link

回答1:

Here you go:

var zoomLevel = 100;
var maxZoomLevel = 105;
var minZoomLevel = 95;

function zoom(zm) {
    var img=document.getElementById("pic");
    if(zm > 1){
        if(zoomLevel < maxZoomLevel){
            zoomLevel++;
        }else{
            return;
        }
    }else if(zm < 1){
        if(zoomLevel > minZoomLevel){
            zoomLevel--;
        }else{
            return;
        }
    }
    wid = img.width;
    ht = img.height;
    img.style.width = (wid*zm)+"px";
    img.style.height = (ht*zm)+"px";
    img.style.marginLeft = -(img.width/2) + "px";
    img.style.marginTop = -(img.height/2) + "px";
}​

You can modify the zoom levels to whatever you want.

I modified the fiddle a bit, since you only need to add javascript to the bottom-left area.