也许我刚刚编写的这个示例将有助于回答您的问题。我已将其发布在jsFiddle here 上,代码如下。这不是一个完美的例子,你的标记和样式可能会有所不同,但希望它展示了一种简单而灵活的方式来组织 JavaScript。最好的方法取决于您的具体要求和可用的工具。
HTML
<button id="toggle">Toggle</button>
<div>
<div id="first" class="toggleable hidden"></div>
<div id="second" class="toggleable hidden"></div>
<div id="third" class="toggleable hidden"></div>
</div>
CSS
div.toggleable {
position: relative;
display: block;
width: 100px;
height: 100px;
top: 100px;
}
div.toggleable.hidden {
display: none;
}
div#first {
background-color: red;
}
div#second {
background-color: blue;
}
div#third {
background-color: green;
}
JavaScript
$(document).ready(function () {
var sliderStates = [
{
"first": "hide",
"second": "hide",
"third": "hide"
},
{
"first": "show",
"second": "hide",
"third": "hide"
},
{
"first": "hide",
"second": "show",
"third": "hide"
},
{
"first": "hide",
"second": "hide",
"third": "show"
}
];
var sliderState = 0;
var incrementState = function() {
sliderState++;
if (sliderState >= sliderStates.length)
sliderState = 1; // Or use 0 if you want to go back to all hidden
}
var show = function($div) {
$div.removeClass("hidden").animate({"left":"75px"}, "slow");
}
var hide = function($div) {
$div.animate({"left":"-1000px"}, function() {
$div.addClass("hidden");
});
}
var showState = function(state) {
$.each(["first", "second", "third"], function(index, element) {
var $div = $("div#" + element);
if (state[element] === "show")
show($div);
else
hide($div);
});
}
$('#toggle').click(function() {
incrementState();
showState(sliderStates[sliderState]);
});
});