簡體   English   中英

CSS3 onclick旋轉和縮放

[英]CSS3 onclick rotate and scale

我創建了一個簡單的效果,即使用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> 

謝謝,任何幫助將不勝感激。

我用您的小提琴來擺弄,並且能夠按照我認為您想要的方式運作。 基本上,您需要檢查圖像是否垂直,並設置最大高度/寬度並考慮邊距偏移和邊界。

現在也已更正,以修復高度>寬度圖像的邊距

更新的小提琴

$(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; 
});

});

嘗試使其適用於任何可能的圖像,我添加了另一個元素,容器,具有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;
}

小提琴

您還可以將scale()添加到transform屬性,並計算圖片的寬度和高度之間的比率。 看到這個小提琴: 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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM