我有下一個問題:我有一個div
其中包含一個圖像。如何用jQuery點擊圖片大小?
我需要調整圖像大小,如果大於div
的寬度,並且用戶單擊圖像,請以全尺寸顯示。
div寬度是用窗口寬度管理的。
我該怎麼做?
我有下一個問題:我有一個div
其中包含一個圖像。如何用jQuery點擊圖片大小?
我需要調整圖像大小,如果大於div
的寬度,並且用戶單擊圖像,請以全尺寸顯示。
div寬度是用窗口寬度管理的。
我該怎麼做?
可以使用的CSS()函數來設置圖像的大小,或者如果你想讓它有點spiffier,您可以使用.animate()爲動畫改變。
說你的圖像的ID是#myimage,這是你將如何做到這一點。
$("#myimage").click(function(){
var imgWidth= $(this).css("width");
var imgHeight = $(this).css("height");
//Checks if the image is already in original size:
if(imgWidth == originalWidth && imgHeight == originalHeight)
{
resizeImage();
}
else
{
$(this).css({width:originalWidth, height: originalHeight});
}
});
這假定你已經保存了圖像的原始大小,否則無法計算出圖像曾經是多大。
編輯:
假設你的div的ID是#mydiv
的$(文件)。就緒()是當網頁加載完成調用。
function resizeImage()
{
var imgWidth= $("#myimage").css("width");
var imgHeight = $("#myimage").css("height");
var divWidth = $("#mydiv").css("width") ;
var divHeight = $("#mydiv").css("height") ;
originalHeight = imgHeight;
originalWidth=imgWidth;
if (imgWidth > divWidth && imgHeight > divHeight)
{
var heightDiff = imgHeight - divHeight;
var widthDiff = imgWidth - divWidth;
//First find out which of the two dimensions is MORE boundry stretching, then we only change that dimension, to keep the image's original proportions.
if(heightDiff>widthDiff)
{
$("#myimage").css("height", divHeight); //Set the
}
else
{
$("#myimage").css("width", divWidth); //Set the width to the div's width
}
}
else if(imgWidth > divWidth)
{
$("#myimage").css("width", divWidth); //Set the width to the div's width
}
else if (imgHeight > divHeight)
{
$("#myimage").css("height", divHeight); //Set the height to the div's height
}
}
$(document).ready(function(){
resizeImage();
});
是的,這是爲了設置原始大小,但是如何首先在負載中設置較小的大小以適合div中的圖像? – 2010-08-07 00:20:21
我添加了一個編輯來解釋如何設置圖像的寬度/高度。這似乎有點複雜,因爲我在高度和寬度都過大的情況下添加了一張支票。在這種情況下,腳本將檢查哪一個超過div MORE,並且只會更改該維度,這樣可以保持圖像的原始比例。 – 2010-08-07 00:31:24
只有錯過了點擊功能才能在縮放圖像和正常圖像之間切換。 – 2010-08-07 00:33:09
如果點擊時不顯示完整大小的圖像,如果它不適合div,你想在哪裏顯示? – ggarber 2010-08-06 23:59:57