在 PC 網頁上,我們常想依據圖片本身的比例來判斷它是橫圖還是直圖,再給予不同的排版方式。手機端的問題更實際:新聞內頁的圖片若照原尺寸塞進窄螢幕,就會溢出容器。
最直接的解法是寫死一段樣式:
.news img{margin:5px auto; display:block;width:100%; height:auto;}
但這會帶來另一個毛病——本來就很小的一張圖,也會被硬撐成 100% 寬,看起來糊成一片。要避開這個問題,就得先讀出圖片的真實尺寸,再決定要不要放大。
var _w = parseInt($(window).width()); // 瀏覽器寬度
$(".new_mess_c img").each(function(i){
var img = $(this);
var realWidth; // 真實寬度
var realHeight; // 真實高度
// $("<img/>") 會建立一個暫時的 img 元素,等同 new Image()
$("<img/>").attr("src", $(img).attr("src")).load(function() {
/* 取得真實寬高有三個重點:
1、必須建立一個 image 物件
2、指定 src
3、一定要在圖片載入完成後(load 回呼中)才讀得到 */
realWidth = this.width;
realHeight = this.height;
if(realWidth >= _w){
$(img).css("width","100%").css("height","auto");
} else {
$(img).css("width", realWidth + 'px').css("height", realHeight + 'px');
}
});
});
window.onload = function(){
function getViewSize() { // 視窗可視範圍
return {
"w": window['innerWidth'] || document.documentElement.clientWidth,
"h": window['innerHeight'] || document.documentElement.clientHeight
};
}
function getFullSize() { // 文件完整尺寸
var w = Math.max(document.documentElement.clientWidth, document.body.clientWidth)
+ Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
var h = Math.max(document.documentElement.clientHeight, document.body.clientHeight)
+ Math.max(document.documentElement.scrollTop, document.body.scrollTop);
w = Math.max(document.documentElement.scrollWidth, w);
h = Math.max(document.documentElement.scrollHeight, h);
return { "w": w, "h": h };
}
var _w = getViewSize()["w"]; // 視情況也可以用 getFullSize()
var Imgarray = document.getElementsByTagName("img");
var realWidth, realHeight;
for(var i = 0; i < Imgarray.length; i++){
var imgtemp = new Image();
imgtemp.src = Imgarray[i].src;
imgtemp.index = i; // 記住是哪一張圖
imgtemp.onload = function(){
var _stemp = this; // 複製指標,否則迴圈中會互相覆蓋
realWidth = this.width;
realHeight = this.height;
if(realWidth >= _w){
Imgarray[_stemp.index].style.width = _w + 'px';
Imgarray[_stemp.index].style.height = 'auto';
} else {
Imgarray[_stemp.index].style.width = realWidth + 'px';
Imgarray[_stemp.index].style.height = realHeight + 'px';
}
};
}
}
jQuery 版本程式碼短、開發快,適合已經在頁面引入 jQuery 的專案;原生版本看起來囉嗦,但少了依賴與包裝,執行效率反而更好。另外提醒一個關鍵細節:無論哪一種寫法,都必須在 onload 之後才讀 width、height,Webkit 系瀏覽器在圖片載入完成前會回報 0。