jQuery attr() change img src

前端 未结 2 806
南笙
南笙 2021-02-13 16:06

I\'m making some Rocket launching effect by jQuery. When I click on Rocket, it\'ll swap with another rocket image, and then launch up. When I click \"Reset\" link, Rocket must r

2条回答
  •  难免孤独
    2021-02-13 16:47

    You remove the original image here:

    newImg.animate(css, SPEED, function() {
        img.remove();
        newImg.removeClass('morpher');
        (callback || function() {})();
    });
    

    And all that's left behind is newImg. Then you reset link references the image using #rocket:

    $("#rocket").attr('src', ...
    

    But your newImg doesn't have an id attribute let alone an id of rocket.

    To fix this, you need to remove img and then set the id attribute of newImg to rocket:

    newImg.animate(css, SPEED, function() {
        var old_id = img.attr('id');
        img.remove();
        newImg.attr('id', old_id);
        newImg.removeClass('morpher');
        (callback || function() {})();
    });
    

    And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/

    UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

    $("#resetlink").click(function(){
        clearInterval(timerRocket);
        $("#wrapper").css('top', '250px');
        $('.throbber, .morpher').remove(); // Clear out the new stuff.
        $("#rocket").show();               // Bring the original back.
    });
    

    And in the newImg.load function, grab the images original size:

    var orig = {
        width: img.width(),
        height: img.height()
    };
    

    And finally, the callback for finishing the morphing animation becomes this:

    newImg.animate(css, SPEED, function() {
        img.css(orig).hide();
        (callback || function() {})();
    });
    

    New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/

    The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

提交回复
热议问题