CSS3 点击旋转和缩放

CSS3 onclick rotate and scale

本文关键字:缩放 旋转 CSS3      更新时间:2023-09-26

我创建了一个简单的效果,使用CSS和jQuery在单击时旋转图像。到目前为止,一切顺利,但是当图像更宽时,我想将其保留在父div内(随着旋转对其进行缩放)。

这里有一个小提琴来澄清我的问题:http://jsfiddle.net/52pxbfcs/2/(只需单击图像即可旋转)。

$(document).ready(function() {
    var angle = 90;
    $(document).on("click", "#parent", function() {	
        $("#img").css ({
            '-webkit-transform': 'rotate(' + angle + 'deg)',
            '-moz-transform': 'rotate(' + angle + 'deg)',
            '-o-transform': 'rotate(' + angle + 'deg)',
            '-ms-transform': 'rotate(' + angle + 'deg)',
        });
        angle+=90; 
    });
	
});
#parent {
    width:140px;
    height:100px;
    border:2px solid #000;
    text-align:center;
}
#img {
     max-width:100%;
    max-height:100%;
	-webkit-transition: all .5s ease-out;
    -moz-transition: all .5s ease-out;
    -ms-transition: all .5s ease-out;
    -o-transition: all .5s ease-out;
    transition: all .5s ease-out;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
    <img src="http://i.ytimg.com/vi/nlobCS5Al8s/maxresdefault.jpg" id="img"/>
</div>

谢谢,任何帮助将不胜感激。

我摆弄了你的小提琴,并能够让它按照我认为你想要的方式工作。基本上,您需要检查图像是否垂直并设置最大高度/wid并考虑边距偏移和边框。

现在也进行了更正,以修复高度>宽度图像的边距

更新的小提琴

$(document).ready(function() {
var angle = 90;
$(document).on("click", "#parent", function() { 
    var normalOrientation = angle % 180 == 0;
    var w = $('#parent').width();
    var h = $('#parent').height();
    var iw = $('#img').width();
    var ih = $('#img').height();
    var border = parseFloat($('#parent').css('border-top-width').replace(/px/,''));
    var marginTop = border + ((Math.max(iw,ih) - Math.min(iw,ih))/2) - ((h - ih)/2);
    $("#img").css ({
        '-webkit-transform': 'rotate(' + angle + 'deg)',
        '-moz-transform': 'rotate(' + angle + 'deg)',
        '-o-transform': 'rotate(' + angle + 'deg)',
        '-ms-transform': 'rotate(' + angle + 'deg)',
        maxHeight : normalOrientation ? '100%' : w,
        maxWidth : normalOrientation ? '100%' : h,
        marginTop: normalOrientation || ih === iw ? 0 : ih > iw ? 0 - marginTop : marginTop
    });
    angle+=90; 
});
});
还可以

transform 属性添加一个scale(),并计算图片宽度和高度之间的比率。看到这个小提琴:http://jsfiddle.net/52pxbfcs/25/

    // within the click function
    var ratio = 1,
        $img = $("#img"),
        $parent = $('#parent');
    if (angle === 90 || angle === 270) {
        ratio = $parent.width() / $img.height();
    }

尝试使其适用于任何可能的图像,我添加了另一个元素,容器,具有 2 种状态

#container {
    width: 140px;
    height: 100px;
    position: absolute;
        -webkit-transition: all .5s ease-out;
    -moz-transition: all .5s ease-out;
    -ms-transition: all .5s ease-out;
    -o-transition: all .5s ease-out;
    transition: all .5s ease-out;  
}
#container.rotated {
    width: 100px;
    height: 140px;
    top: 20px;
    left: 20px;
}

小提琴