在網頁中顯示多張圖片,並且 width 用百分比佈局,高度隨內容擴展,每張圖片的長寬不一,如何達到一個比較好的顯示效果呢?
我是打算每張圖片以正方形排列,問題是每張圖片的長寬不一,若固定大小顯示就會拉扯。
解決方法:用<ul><li>,固定<li>的大小,顯示<li>大小的圖片,多於部分隱藏。
1.用百分比佈局是爲了可以在一個容器方便地顯示要求數量的圖片,若使用固定的像素值,則父輩容器長寬改變子容器也得改變。但是用百分比佈局無法知道容器的真實width值。所以,固定<li>大小爲正方形的方法:
$(".pic-ul li").height($(".pic-ul li").width() );
2.圖片可能過大或過小,使顯示一小部分或出現留白。解決方法:使圖片窄的一邊充滿容器。
if (img.height < img.width ) {
img.style.height="100%";
}else{
img.style.width="100%";
}
圖片上傳並回顯:
HTML:
<div class="center-c">
<div class="writer-center">
<div id="result"><ul class="pic-ul"></ul><div style="clear:both"></div></div><!--顯示圖片-->
</div>
<p>
<a href="javascript:void(0)" class="pic" title="圖片">
<input type="file" id="file" class="pic-file" name="file" accept=".jpg,.gif,.png">
<img src="tp2.png" width="25"/></a>
</p>
</div>
css:
*{ border:0; outline:0; font-family:Arial, Helvetica, Sans-Serif; vertical-align:baseline;list-style:none; text-decoration:none;margin:0; padding:0;}
html{font-size:62.5%;overflow-x:hidden;}
body{ font-size:14px; font-size:1.4rem; background:url(../img/bj4.jpg);}
a,a:hover,a:visited,a:active,a:link{text-decoration:none; color:#666;}
.center-c {width:80%;margin-left:10%; margin-top:50px}
.writer-center{ width:100%; min-height:110px;box-shadow:0 0 10px 0 #CCC inset;background-color:#fff; border:#CCC thin solid;}
/*上傳圖片顯示*/
.pic{ position:relative; cursor:pointer;}
.pic-file{position:absolute; opacity:0; width:100%; height:auto; top:0; right:0;}
#result{width:96%; margin:10px 2%; }
#result li{float:left; width:33%; height:170px; overflow:hidden; margin-left:0.1%; border:#F1F1F1 thin solid;}
JavaScript:
$(document).ready(function(){
//圖片上傳
function ProcessFile(e) {
var file = document.getElementById('file').files[0];
if (file) {
var reader = new FileReader();
reader.onload = function (event) {
var txt = event.target.result;
var img = document.createElement("img");
img.src = txt;
//調整圖片大小
img.onload = function(){
if (img.height < img.width ) {
img.style.height="100%";
}else{
img.style.width="100%";
}
}
var pli=$("<li></li>").html(img );
$(".pic-ul").append(pli);
$(".pic-ul li").height($(".pic-ul li").width() ); /*使圖片正方形獲取div的寬度,設置div正方形*/
};
}
reader.readAsDataURL(file);
}
function contentLoaded() {
document.getElementById('file').addEventListener('change',ProcessFile, false);
}
window.addEventListener("DOMContentLoaded", contentLoaded, false);
/*end of 上傳圖片*/
});
最終效果: