前言
相信大家在日常的web開發(fā)中,作為前端經(jīng)常會遇到處理圖片拉伸問題的情況。
例如banner、圖文列表、頭像等所有和用戶或客戶自主操作圖片上傳的地方,而一旦牽扯圖片,就會涉及到圖片拉伸的問題,當然,在圖片上傳時做手動裁切,讓用戶或客戶清晰的感知到圖片的有效內(nèi)容才是最優(yōu)的解決方案,但是在其他各種外在因素下,沒有做裁切的話,就需要在前端顯示上做處理了,滿足在上傳任意大小圖片的情況下,最優(yōu)顯示效果的需求。
這時我們需要考慮到極端效果,如下圖:
而我們想要得到的效果是這樣的------
把圖片放進框框,要幾步?三步...我們開始
第一步:先畫個框框 (這里順便安利一種自適應框框的方法)
// 假定需要一個在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 ); //執(zhí)行寬高比對并設置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頁面成也圖片,敗也圖片,拉伸了圖片就等著設計師的磨嘰吧,哈哈哈哈...
總結
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com