我正在尝试通过单击另一个 div 时淡入淡出来交换 div。唯一的问题是:首先回调函数不会被调用,所以我把它完全去掉,现在 div 表现得很有趣。这意味着当我单击其中一个 div 时,应该淡入的相应 div 没有,而应该淡出的 div 没有。
HTML:
<ul id="tour">
<li id="pitch_link" class="selected">
<h1>Pitch</h1>
<p>Pitch a ball.</p>
</li>
<li id="publish_link">
<h1>Publish</h1>
<p>Publish the spin.</p>
</li>
<div id="pitch">
<ul>
<li><h2>pitch Stuff</h2></li>
<li><h2>Graphics</h2></li>
</ul>
</div>
<div id="publish">
<ul>
<li><h2>publish Stuff</h2></li>
<li><h2>Graphics</h2></li>
</ul>
</div>
不带回调的 jQuery:
$("#tour li").click( function(event) {
if( !$(this).is( ".selected" ) ) {
// find the link that was previously selected and fade it out
var prevSelectedLink = $(".selected").attr( 'id' );
prevSelectedID = "#" + prevSelectedLink.substr( 0, prevSelectedLink.length-5 );
// fade the previously selected div out
$(prevSelectedID).fadeOut( "fast" );
// Deselect the previously selected link (remove selected class)
$(prevSelectedLink).removeClass( "selected" );
// Select the new Link
$(this).addClass("selected");
// Fade the new div content in
var linkID = $(this).attr( 'id' ); // linkID = pitch_link
contentID = "#" + linkID.substr( 0, linkID.length-5 ); // contentID = #pitch
$(contentID).fadeIn( "slow" );
}
});
带回调的 jQuery: 如果( !$(this).is( ".selected") ) {
// find the link that was previously selected and fade it out
var prevSelectedLink = $(".selected").attr( 'id' );
prevSelectedID = "#" + prevSelectedLink.substr( 0, prevSelectedLink.length-5 );
// fade the previously selected div out
$(prevSelectedID).fadeOut( "fast" , function() {
// Deselect the previously selected link (remove selected class)
$(prevSelectedLink).removeClass( "selected" );
// Select the new Link
$(this).addClass("selected");
// Fade the new div content in
var linkID = $(this).attr( 'id' ); // linkID = pitch_link
contentID = "#" + linkID.substr( 0, linkID.length-5 ); // contentID = #pitch
$(contentID).fadeIn( "slow" );
});
}
});
最佳答案
如果没有 CSS,我真的无法判断问题出在哪里,但可以像这样清理代码:
$('#tour li').click(function(){
if( !$(this).hasClass('selected') ){
//Get the ID of the DIV you want to show
var div_id = $(this).attr( 'id' ).replace('_link','');
$('#tour li').removeClass('selected');
$(this).addClass('selected');
$('div').fadeOut("fast", function(){
$('#'+div_id).fadeIn("fast");
});
}else{
return false;
}
});
我还没有对此进行测试,但它的作用是如果未选择链接,它会使用链接 ID 获取 div 的 ID,从所有其他链接中删除“selected”类并添加“selected”类到李点击。然后所有的 div 都淡出,最后所需的 div 淡入。
您还可以使用 .not() 运算符来防止带有“div_id”的 div 的 fadeOut()。
关于javascript - jQuery fadeOut 回调函数未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8796925/