2

使用此stackoverflow 线程中的一些代码,我正在尝试开发一个类似于此Web 模板上的内容滑块

这是我工作的 jsfiddle

您单击链接以显示内容;之前显示的内容在此之前被隐藏。如果某些内容正在显示,可以通过单击手动隐藏它。

使用链接的 ID(A、B 等),我们得到<div>要显示的内容的 ID ( )。当一个元素被显示时,它被赋予类,“elementEnabled”,以便稍后识别它。

在我滑入新内容之前,我希望隐藏的内容不碍事。我如何有条不紊地做到这一点?我.delay().show()一个很好的方法来做到这一点吗?

有没有更优雅的方式(在 jQuery 中)系统地隐藏显示的内容,然后显示适当的内容?有没有比使用更好的方法 $.when().then(function(){})???将这么多代码放在回调函数中(如下所示)是一种好习惯,还是应该将代码的“显示”部分拆分为单独的函数?

感谢您的任何建议。

的HTML:

<div id="links">
<a href="#" id="a-link">A</a>
<a href="#" id="b-link">B</a>
</div>
<div id="wrap">
<div class="start-content" id="a">
content here
</div>    
<div class="content" id="b">
content here
</div>
</div>

这是javascript:

$("#links a").click(function() {

//  having to do this for the callback function below
var park_this = $(this);

//  which ID is currently shown?
id_enabled = $('.enabledElement').attr("id").replace('-link', '');           

//hide previously displayed content
$.when($('#' + id_enabled).stop().hide("slide", 
    { direction: "left" }, 400)).then( function(){ // callback 

// remove any instances of special class
$('.enabledElement').removeClass('enabledElement');

// add special class to clicked element 
park_this.addClass('enabledElement');

// using the link ID, get the ID of the content to show
var id = park_this.attr("id").replace('-link', ''); //matching id

//show what's clicked on
$('#' + id).stop().delay(initial_pause).show("slide", 
    { direction: "left" }, 1000 );    

});  // close when/then callback function

} // close "click" function
4

0 回答 0