這次給大家帶來JS怎樣阻止圖片拉伸自適應,JS阻止圖片拉伸自適應的注意事項有哪些,下面就是實戰案例,一起來看一下。
前言
相信大家在日常的web開發中,作為前端經常會遇到處理圖片拉伸問題的情況。
例如banner、圖文列表、頭像等所有和用戶或客戶自主操作圖片上傳的地方,而一旦牽扯圖片,就會涉及到圖片拉伸的問題,當然,在圖片上傳時做手動裁切,讓用戶或客戶清晰的感知到圖片的有效內容才是最優的解決方案,但是在其他各種外在因素下,沒有做裁切的話,就需要在前端顯示上做處理了,滿足在上傳任意大小圖片的情況下,最優顯示效果的需求。
把圖片放進框框,要幾步?三步...我們開始
第一步:先畫個框框 (這里順便安利一種自適應框框的方法)
// 假定需要一個在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> <p id="list"> <p class="img-box"> <img src="..."/> </p> </p> </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頁面成也圖片,敗也圖片,拉伸了圖片就等著設計師的磨嘰吧,哈哈哈哈...
相信看了本文案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
推薦閱讀:
Jstree選中父節點時禁用子節點也被選中
Swiper里自定義分頁器使用步奏詳解
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com