防止圖片拉伸的自適應處理

在web開發中,做爲前端常常會遇處處理圖片拉伸問題的狀況。
例如banner、圖文列表、頭像等全部和用戶或客戶自主操做圖片上傳的地方,
而一旦牽扯圖片,就會涉及到圖片拉伸的問題,
固然,在圖片上傳時作手動裁切,讓用戶或客戶清晰的感知到圖片的有效內容纔是最優的解決方案,
可是在其餘各類外在因素下,沒有作裁切的話,就須要在前端顯示上作處理了,
知足在上傳任意大小圖片的狀況下,最優顯示效果的需求。css

這時咱們須要考慮到極端效果,以下圖:
圖片描述前端

而咱們想要獲得的效果是這樣的------
圖片描述web

把圖片放進框框,要幾步?三步...咱們開始dom

第一步:先畫個框框 (這裏順便安利一種自適應框框的方法)
//  假定須要一個在750px屏幕下寬400px,高280px的盒子
//  寬度 = 400 / 750 = 0.5333
//  高度 = 280 / 400 * 0.5333 = 0.3733

<style>
    .img-box{
        position: relative;
        width: 53.33%;
        height: 0;
        padding-bottom: 37.33%;
        overflow: hidden;
        background-color: #eee;
    }
</style>

<body>
    <div id="list">
        <div class="img-box">
            <img src="..."/>
        </div>
    </div>
</body>
第二步:設置圖片須要使用到的css
<style>
    .width{
        position: absolute !important;
        width: 100% !important;
        min-height: 100% !important;
        top: 50% !important;
        transform: translateY(-50%) !important;
        -ms-transform: translateY(-50%) !important;
        -moz-transform: translateY(-50%) !important;
        -webkit-transform: translateY(-50%) !important;
        -o-transform: translateY(-50%) !important;
        display: block;
    }
    .height{
        position: absolute !important;
        height: 100% !important;
        min-width: 100% !important;
        left: 50% !important;
        transform: translateX(-50%) !important;
        -ms-transform: translateX(-50%) !important;
        -moz-transform: translateX(-50%) !important;
        -webkit-transform: translateX(-50%) !important;
        -o-transform: translateX(-50%) !important;
        display: block;
    }
</style>
第三步:js獲取圖片高度比較並給img添加類名
//須要注意的是,不能在css中直接給img設置寬度和高度
//不然在img.onload後獲取的寬高是css設置的寬高
//同時建議使用dom對象來獲取img標籤
<script>
    var list = document.getElementById('list');
    getImgWH ( list );
    //執行寬高比對並設置img類名
    function getImgWH ( Obj ) {
        var img = Obj.getElementsByTagName('img');
        for( var i=0 ; i<img.length ; i++ ){
            img[i].onload = function(){
                var width  = this.width;
                var height = this.height;
                if ( width > height ) {
                    this.classList.add('height');
                } else if ( width < height ) {
                    this.classList.add('width');
                } else {
                    this.style.width  = '100%';
                    this.style.height = '100%';
                }
            }
        }
    }
</script>

圖片防止拉伸處理比較簡單,可是在實際項目中須要獲得足夠的重視,
一個web頁面成也圖片,敗也圖片,
拉伸了圖片就等着設計師的磨嘰吧,哈哈哈哈...this

相關文章
相關標籤/搜索