簡體   English   中英

在jQuery中使用attr()后,如何為圖像添加效果?

[英]How can I add effect to an image after using the attr() in jQuery?

情況

我有一個btn圖像 我想在用戶單擊btn時更改圖像的src。

然后,我想給它添加一些效果,例如fadeIn('slow');


我試過了

附加我的fadeIn('slow'); attr()的末尾,但沒有任何效果。

$('#id').click(function(e) {
    e.preventDefault();

    $('#img').attr('src','/path/car.png').fadeIn('slow');  <-----HERE

});

我也嘗試過

移動我的fadeIn('slow'); 到下一行,但我也沒有任何效果。

$('#id').click(function(e) {
    e.preventDefault();

    $('#img').attr('src','/path/car.png');
    $('#img').fadeIn('slow');  <-----HERE

});

有人可以幫我解決這個問題嗎?

第一次使用fadeOut ,一旦完成使用fadeIn

 $('#id').click(function(e) { e.preventDefault(); $('#img').fadeOut('slow', function(){ $('#img').attr('src','http://icons.iconarchive.com/icons/crountch/one-piece-jolly-roger/256/Zoro-icon.png').fadeIn('slow'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="id">Click me</button><br /> <img id="img" src="http://icons.iconarchive.com/icons/crountch/one-piece-jolly-roger/256/Luffys-flag-icon.png" /> 

在這里,我舉了一個示例,您可以多次更改圖像的src:

$("#b1").on("click", function(){
    $("img")
        .finish().hide() // pay attention on this line -> it will end any fadeIn and then hide to do a new fadeIn
        .attr("src", "https://www.petfinder.com/wp-content/uploads/2012/11/dog-how-to-select-your-new-best-friend-thinkstock99062463.jpg")
        .fadeIn(2000);
});

$("#b2").on("click", function(){
    $("img")
        .finish().hide() // pay attention on this line -> it will end any fadeIn and then hide to do a new fadeIn
        .attr("src", "http://blogs.psychcentral.com/life-goals/files/2014/09/cute-dog-pup.jpg")
        .fadeIn(2000);
});

$("#b3").on("click", function(){
    $("img")
        .finish().hide() // pay attention on this line -> it will end any fadeIn and then hide to do a new fadeIn
        .attr("src", "http://upload.wikimedia.org/wikipedia/commons/1/13/Clyde_The_Bulldog.jpg")
        .fadeIn(2000);
});

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM