CSS Transform with element resizing

后端 未结 3 1594
北恋
北恋 2020-12-04 17:39

I found this: width/height after transform

and several others, but nothing is not quite what I\'m looking for. What I want is to scale something to 50% of it\'s siz

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 18:05

    The problem I noticed is that when element scales, browser change its pixels ratio, not pixels amount. Element is smaller but it doesn't change its actual pixel size in DOM. Because of that I don't think that CSS-only solution exist.

    I put scalable element into container which keeps the same pixel ratio as rest of elements. Using Java Script I simply change container's size. Everything is still based on CSS3 transform: scale. Maybe JS code could be simplier, but now it's all about the idea (just a proof of concept);) Fiddle with two examples: http://jsfiddle.net/qA5Tb/9/

    HTML:

    Nunc et nisi ante. Integer in blandit nisi. Nulla facilisi. Vestibulum vulputate sapien eget mauris elementum sollicitudin. Nullam id lobortis dolor. Nulla vitae nibh vitae sem volutpat pretium. Nunc et nisi ante. Integer in blandit nisi. Nulla facilisi. Vestibulum vulputate sapien eget mauris elementum sollicitudin. Nullam id lobortis dolor. Nulla vitae nibh vitae sem volutpat pretium.

    CSS:

    .overall-scalable {width: 350px; height: 150px; overflow: hidden; -webkit-transition: all 1s;}
    .scalable {color: #666; width: 350px; height: 150px; -webkit-transform-origin: top left; -webkit-transition: all 1s;}
    

    JS:

    $('button').click(function() {
        $('.scalable').each(function(){
            rescale($(this));
        })
    });
    
    function rescale(elem) {
    
        var height = parseInt(elem.css('height'));
        var width = parseInt(elem.css('width'));
        var scalex = parseFloat(elem.attr('scalex'));
        var scaley = parseFloat(elem.attr('scaley'));
    
        if (!elem.hasClass('rescaled')){
            var ratioX = scalex;
            var ratioY = scaley;
        }else{          
            var ratioX = 1;
            var ratioY = 1;
        }
    
        elem.toggleClass('rescaled');
        elem.css('-webkit-transform', 'scale('+ratioX +', '+ratioY+')');        
        elem.parent().css('width', parseInt(width*ratioX) + 'px');
        elem.parent().css('height', parseInt(height*ratioY) + 'px');
    }​
    

提交回复
热议问题