JS獲取圖片實際寬高及根據圖片大小進行自適應
更新時間:2013年08月11日 18:56:16 作者:
圖片實際寬高使用js進行獲取以及根據圖片大小進行自適應,此功能個人感覺比較實用,在此貢獻出來,希望對大家有所幫助
JS獲取圖片實際寬高,以及根據圖片大小進行自適應
<img src="http://xxx.jpg" id="imgs" onload="adapt();"/>
function adapt(){
var tableWidth = $("#imgTable").width(); //表格寬度
var img = new Image();
img.src =$('#imgs').attr("src") ;
var imgWidth = img.width; //圖片實際寬度
if(imgWidth<tableWidth){
$('#imgs').attr("style","width: auto");
}else{
$('#imgs').attr("style","width: 100%");
}
}
另可設置CSS樣式:
<style type="text/css">
<!--
img{
max-width:100%;height:auto;
}
-->
</style>
復制代碼 代碼如下:
<img src="http://xxx.jpg" id="imgs" onload="adapt();"/>
復制代碼 代碼如下:
function adapt(){
var tableWidth = $("#imgTable").width(); //表格寬度
var img = new Image();
img.src =$('#imgs').attr("src") ;
var imgWidth = img.width; //圖片實際寬度
if(imgWidth<tableWidth){
$('#imgs').attr("style","width: auto");
}else{
$('#imgs').attr("style","width: 100%");
}
}
另可設置CSS樣式:
復制代碼 代碼如下:
<style type="text/css">
<!--
img{
max-width:100%;height:auto;
}
-->
</style>
相關文章
TypeScript泛型參數默認類型和新的strict編譯選項
這篇文章主要介紹了TypeScript泛型參數默認類型和新的strict編譯選項,對TypeScript感興趣的同學,可以參考下2021-05-05JavaScript中prompt()函數的用法實戰(zhàn)例子
JavaScript中的prompt是一個函數,用于在瀏覽器中顯示一個對話框,提示用戶輸入一些信息,這篇文章主要給大家介紹了關于JavaScript中prompt()函數的用法實戰(zhàn),需要的朋友可以參考下2023-11-11