【发布时间】:2011-06-23 11:52:29
【问题描述】:
我有一个带有图像的图像。例如:
<img id='imageWord' src=images\Card.png onclick='changeImage();'>
当用户点击它时,我想做一个fadeOut,将它的src更改为另一个图像,然后fadeIn。 p>
function changeImage()
{
$('#ImageWord').animate({opacity:0})
.queue(function(){
$(this).attr("src", '');
replaceImage('#ImageWord', 'images\newImage.png');
$(this).dequeue()
})
.animate({opacity:1});
}
var MAX_HEIGHT = 260;
var MAX_WIDTH = 260;
function keepAspectRatio(temp, target, url)
{
$(target).removeAttr('style');
// Get height and width once loaded
var realHeight = temp.height;
var realWidth = temp.width;
// Get how much to divide by (1 if image fits in dimensions)
// Get rid of ", 1" if you just want everything to be either
// MAX_HEIGHT tall or MAX_WIDTH wide
var factor = Math.max(realHeight/MAX_HEIGHT, realWidth/MAX_WIDTH, 1);
realHeight /= factor;
realWidth /= factor;
// Set the target image's source, height and width
$(target).attr("src", url).css({height: realHeight, width: realWidth});
if (realWidth != MAX_WIDTH)
{
var offsetX = (MAX_WIDTH - realWidth ) / 2;
var sum = parseFloat($(target).css("left").replace("px", "")) + offsetX;
$(target).css("left", sum);
}
if (realHeight != MAX_HEIGHT)
{
var offsetY = (MAX_HEIGHT - realHeight) / 2;
var sum = parseFloat($(target).css("top").replace("px", "")) + offsetY;
$(target).css("top", sum);
}
}
function replaceImage($target, url) {
$("<img>").load(function() {
keepAspectRatio(this, $target, url);
}).attr("src", url);
}
有时我会看到以下内容:
- Card.png 淡出。
- 无图像(0.1 秒)
- 再次 Card.png(0.1 秒)。
- newImage.png 淡入。
我想避免第 3 步。
有什么建议吗?
【问题讨论】:
标签: javascript html image fadein fadeout