JavaScript等比例縮放圖片控制超出范圍的圖片
更新時(shí)間:2013年08月06日 15:56:40 作者:
當(dāng)網(wǎng)頁加載一個(gè)尺寸比較大的圖片時(shí),往往會(huì)把一個(gè)網(wǎng)頁撐的變形,頁面變得很難看,于是我們就想到了用JS去控制超出一定范圍的圖片
js等比例縮放圖片,這個(gè)功能非常實(shí)用,當(dāng)網(wǎng)頁加載一個(gè)尺寸比較大的圖片時(shí),往往會(huì)把一個(gè)網(wǎng)頁撐的變形,頁面變得很難看,于是我們就想到了用JS去控制超出一定范圍的圖片,腳本之家以穩(wěn)定頁面布局,本代碼段就是完成了此功能,而且代碼非常簡潔,效果很好。
<html><head><title>等比例縮放圖片</title><script>function
DrawImage(ImgD,iwidth,iheight){ //參數(shù)(圖片,允許的寬度,允許的高度)
var
image=new Image(); image.src=ImgD.src;
if(image.width>0
&& image.height>0){ if(image.width/image.height>=
iwidth/iheight){ if(image.width>iwidth){
ImgD.width=iwidth;
ImgD.height=(image.height*iwidth)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
}else{
if(image.height>iheight){
ImgD.height=iheight;
ImgD.width=(image.width*iheight)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
}
}
}
</script></head><body><img
src=http://www.dbjr.com.cn/uploadfile/2013/0803/20130803034531502.jpg"
alt="自動(dòng)縮放后的效果"
width="100"
height="100"
onload="javascript:DrawImage(this,80,80)"
/></body></html>
復(fù)制代碼 代碼如下:
<html><head><title>等比例縮放圖片</title><script>function
DrawImage(ImgD,iwidth,iheight){ //參數(shù)(圖片,允許的寬度,允許的高度)
var
image=new Image(); image.src=ImgD.src;
if(image.width>0
&& image.height>0){ if(image.width/image.height>=
iwidth/iheight){ if(image.width>iwidth){
ImgD.width=iwidth;
ImgD.height=(image.height*iwidth)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
}else{
if(image.height>iheight){
ImgD.height=iheight;
ImgD.width=(image.width*iheight)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
}
}
}
</script></head><body><img
src=http://www.dbjr.com.cn/uploadfile/2013/0803/20130803034531502.jpg"
alt="自動(dòng)縮放后的效果"
width="100"
height="100"
onload="javascript:DrawImage(this,80,80)"
/></body></html>
您可能感興趣的文章:
相關(guān)文章
CSS+Table圖文混排中實(shí)現(xiàn)文本自適應(yīng)圖片寬度(超簡單+跨所有瀏覽器)
最近在為學(xué)樂網(wǎng)開發(fā)圖片顯示功能時(shí)遇到一個(gè)問題:在一個(gè)table中有兩行,上邊顯示圖片(大小隨機(jī)),下邊顯示對圖片的相關(guān)說明(文字長度隨機(jī))2009-02-02js的form表單提交url傳參數(shù)(包含+等特殊字符)的兩種解決方法
下面小編就為大家?guī)硪黄猨s的form表單提交url傳參數(shù)(包含+等特殊字符)的兩種解決方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-05-05