本文為大家分享了四個jquery圖片常見操作,供大家參考,具體內容如下
1、關于圖片大小的重繪,你可以在服務端來實現,也可以通過JQuery在客戶端實現。
$(window).bind("load", function() { // IMAGE RESIZE $('#product_cat_list img').each(function() { var maxWidth = 120; var maxHeight = 120; var ratio = 0; var width = $(this).width(); var height = $(this).height(); if(width > maxWidth){ ratio = maxWidth / width; $(this).css("width", maxWidth); $(this).css("height", height * ratio); height = height * ratio; } var width = $(this).width(); var height = $(this).height(); if(height > maxHeight){ ratio = maxHeight / height; $(this).css("height", maxHeight); $(this).css("width", width * ratio); width = width * ratio; } }); //$("#contentpage img").show(); // IMAGE RESIZE});
2、jQuery獲取<img>圖片實際尺寸的方法
$(function(){ var imgSrc = $("#image").attr("src"); getImageWidth(imgSrc,function(w,h){ console.log({width:w,height:h}); });});function getImageWidth(url,callback){ var img = new Image(); img.src = url; // 如果圖片被緩存,則直接返回緩存數據 if(img.complete){ callback(img.width, img.height); }else{ // 完全加載完畢的事件 img.onload = function(){ callback(img.width, img.height); } } }
3、jquery 自動調整圖片大小
$(document).ready(function(){ $('img').each(function() { var maxWidth =500; // 圖片最大寬度 var maxHeight =500; // 圖片最大高度 var ratio = 0; // 縮放比例 var width = $(this).width(); // 圖片實際寬度 var height = $(this).height(); // 圖片實際高度 // 檢查圖片是否超寬 if(width > maxWidth){ ratio = maxWidth / width; // 計算縮放比例 $(this).css("width", maxWidth); // 設定實際顯示寬度 height = height * ratio; // 計算等比例縮放后的高度 $(this).css("height", height); // 設定等比例縮放后的高度 } // 檢查圖片是否超高 if(height > maxHeight){ ratio = maxHeight / height; // 計算縮放比例 $(this).css("height", maxHeight); // 設定實際顯示高度 width = width * ratio; // 計算等比例縮放后的高度 $(this).css("width", width); // 設定等比例縮放后的高度 }}); });
4、使用jQuery對圖片進行大小縮放
$(window).bind("load", function() { // IMAGE RESIZE $('#product_cat_list img').each(function() { var maxWidth = 120; var maxHeight = 120; var ratio = 0; var width = $(this).width(); var height = $(this).height(); if(width > maxWidth){ ratio = maxWidth / width; $(this).css("width", maxWidth); $(this).css("height", height * ratio); height = height * ratio; } var width = $(this).width(); var height = $(this).height(); if(height > maxHeight){ ratio = maxHeight / height; $(this).css("height", maxHeight); $(this).css("width", width * ratio); width = width * ratio; } }); //$("#contentpage img").show(); // IMAGE RESIZE});
以上就是本文的全部內容,幫助大家實現圖片重繪、圖片獲取尺寸、圖片調整大小以及圖片縮放,希望大家喜歡。
新聞熱點
疑難解答