问题
This might seem as child play, but I can't figure out how I can replace the src attribute of an image.
The src is "build.php" which generate the image. What I want is when I click on "mix" it will run build.php to generate a new image, remove the old image and display the new image with a nice fadeout/fadein.
Also with an "Building new image" which hides when the new image is done loading.
I tried with
$("#mix").click(function(){
var img = new Image();
$(img).load(function () {
$(this).hide();
$('#loader').removeClass('loading').append(this);
$(this).fadeIn();
}).attr('src', 'build.php');
});
But the 2nd time I click on "mix" it will place new image under the old image, not remove the old image.
回答1:
$("#mix").click(function(){
var img = new Image();
$(img).load(function () {
$(this).hide();
$('#loader').removeClass('loading').append(this);
$(this).fadeIn();
}).attr('src','').attr('src', 'build.php');
});
Look below - works :
$(document).ready(function() {
$("#yourimagediv").click(function() {
$("#yourimagediv").attr("src","image.php?"+new Date().getTime());
});
});
<img id="yourimagediv" src="image.php" />
回答2:
var mix = $('#mix'),
jqImage = $('#brick-image');
mix.on('click', function (e) {
var img = new Image();
jqImage.fadeOut();
img.onload = function () {
jqImage.attr('src', img.src);
jqImage.fadeIn();
};
// add param to prevent caching of build.php image
img.src = 'build.php?' + new Date().getTime();
e.preventDefault();
});
来源:https://stackoverflow.com/questions/12476646/replace-img-src-with-jquery-on-click