<html>
<head>
<style>
* {margin: 0;}
div {text-align:center;}
</style>
</head>
<body>
<div>
<img src="res/waitAni1.gif" id="loading"/></div>
<div>
<img src="" id="show" style="visibility:hidden;"/>
</div>
<script>
var urlarg ={};
var img = document.getElementById('show');
var maxHeight = '600';
var maxWidth = '800';
function getarg()
{
var url = decodeURI(window.location.href);
var allargs = url.split("?")[1];
var args = allargs.split("&");
for(var i=0; i<args.length; i++)
{
var arg = args[i].split("=");
urlarg[arg[0]] = arg[1];
}
}
function setXY()
{
var width = img.width;
var height = img.height;
var rate = width/height;
if(width > maxWidth )
{
width = maxWidth;
height = width/rate;
}
if(height > maxHeight)
{
height = maxHeight;
width = height*rate;
}
img.width = width;
img.height = height;
}
function setSRC()
{
if(!urlarg.src)
{
urlarg.src = '';
return;
}
img.onload = function(){
if(urlarg.width)
{
maxWidth = urlarg.width;
}
if(urlarg.height)
{
maxHeight = urlarg.height;
}
document.getElementById('loading').style.display = 'none';
setXY();
marginIMG(img);
img.style.visibility = 'visible';
}
img.src = urlarg.src;
}
function load()
{
getarg();
marginIMG(document.getElementById('loading'));
setSRC();
document.body.oncontextmenu = function (e){return false;};
}
function marginIMG(obj)
{
if(maxHeight > obj.height)
{
obj.style.marginTop = (maxHeight - obj.height)/2;
obj.style.marginBottom = (maxHeight - obj.height)/2;
}
if(maxWidth > img.width)
{
obj.style.marginLeft = (maxWidth - obj.width)/2;
obj.style.marginRight = (maxWidth - obj.width)/2;
}
}
load();
</script>
</body>
</html>
在製作的過程中發現,當你調整img對象的長或者寬時,另外一項會隨着同比改變,於是就有了我的第一版程序
function setXY()
{
if(img.width > maxWidth)
{
img.width = maxWidth;
}
if(img.height > maxHeight)
{
img.height = maxHeight;
}
}
在我的意識中,這個應該會產生不變形的,最長邊等於我設定該邊的最大值
開始拿了幾個圖片都沒有問題,昨天他換了一個長寬高都很大的圖片,竟然變形了.
測試了半天才發現,原來,當你設定了img的一個邊以後,再設置另外一個邊的時候,先前設置的邊不會跟着變化
例如 原圖 1000*1000 我們要調整其在800*600的範圍顯示
正確的長寬應該是 600*600
當我將width設置成800的時候 height 變爲800
這個時候程序會再次設置height爲600
,出乎以外的是,width竟然沒有變成600
經過修改代碼應該是
function setXY()
{
var width = img.width;
var height = img.height;
var rate = width/height;
if(width > maxWidth )
{
width = maxWidth;
height = width/rate;
}
if(height > maxHeight)
{
height = maxHeight;
width = height*rate;
}
img.width = width;
img.height = height;
}