简体   繁体   中英

How to convert css pixels to css3 scale (x,y)

I have a div whose initial width and height are set by the user. When a user zooms in the browser(ctrl+ or ctrl-) the initial width and height of that div changes, say a user zooms in 175%, the aspect ratio of that div stays the same because the width and height is adjusted. Is there a way to replicate this by dynamically setting transform: scale(x,y). I have tried several thing but can't seem to find a solid solution.

Solution seems pretty straight-forward. Store scale somewhere, then increase/decrease it on button's click:

(function () {
  function zoom(element, scale) {
    element.style.webkitTransform =
      element.style.transform = 'scale(' + scale + ')';
    return scale;
  }
  
  var zoomable = document.querySelector('.zoomable');
  var scale = 1;
  
  document.querySelector('#zoomin')
    .addEventListener('click', function () {
      scale = zoom(zoomable, scale * 2);
    });
  
  document.querySelector('#zoomout')
    .addEventListener('click', function () {
      scale = zoom(zoomable, scale * 0.5);
    });
})();

Demo: http://jsbin.com/aJagofU/1/edit?js,output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM