2009-05-28 62 views
0
$('<div class="error"></div>').html('<h2>(click here to dismiss)</h2>').insertAfter($('#someid')).fadeIn('slow').animate({ opacity: 1.0 }, 1000).click(function() { 
     $(this).fadeOut('slow', function() { 
      $(this).remove() 
     }) 
    }); 

有沒有辦法將它與組合:淡出說明書(點擊)具有自動(後幾秒鐘)

$('#someid').animate({opactiy: 1.0 } fadeOut('slow', function() { 
      $(this).remove() 
     }); 

換句話說,它結合起來,所以當他們不點擊,它會在這麼多秒後消失..

回答

2

我不確定是否有一種很好的方法將所有這些鏈接在一起,所以它發生在一個命令中。但是,您可以在另一行上使用setTimeout來在另一個語句中實現相同的效果。例如,你的第一個語句後:

setTimeout(function() { 
    if ($('#someid').css('opacity') == 1.0) { 
     // Fade out has not started yet 
     $('#someid').animate({opactiy: 1.0 } fadeOut('slow', function() { 
      $(this).remove() 
     }); 
    } 
}, 3000); // setTimeout counted in ms, not seconds 

我同意,這可能是更優雅,以鏈都在一起,但我不知道的一個好辦法做到這一點。作爲一個方面說明,你可以在JavaScript中的方法名稱之間使用盡可能多的空格,這樣你可以將原來的語句分解成多行,以提高可讀性,例如,

$('<div class="error"></div>') 
    .html('<h2>(click here to dismiss)</h2>') 
    .insertAfter($('#someid')) 
    .fadeIn('slow') 
    .animate({ opacity: 1.0 }, 1000) 
    .click(function() { 
    $(this).fadeOut('slow', function() { 
     $(this).remove() 
    }) 

});

但這是一個偏好問題。