题
我有一个正常工作的jQuery动画脚本,但是,我觉得有一种方法可以减少脚本的整体开销。这是开发页面的链接:
http://dev.abinstallations.com
动画有两个部分,这些动画适用于六个单独的分配元素。每个元素都应用一个单独的脚本。例如:
//First
$("#first_flip").hide();
$("#first_button_show").click(function(){
$('#first_flip').animate({
opacity: 'toggle',
top: '+=524',
height: 'toggle'}, 600, function() {
// Animation complete.
});
});
$("#first_button_hide").click(function(){
$('#first_flip').animate({
opacity: 'toggle',
top: '-=524',
height: 'toggle'}, 400, function() {
// Animation complete.
});
});
//Second
$("#second_flip").hide();
$("#second_button_show").click(function(){
$('#second_flip').animate({
opacity: 'toggle',
top: '+=524',
height: 'toggle'}, 600, function() {
// Animation complete.
});
});
$("#second_button_hide").click(function(){
$('#second_flip').animate({
opacity: 'toggle',
top: '-=524',
height: 'toggle'}, 400, function() {
// Animation complete.
});
});
...依此类推,其余四个要素。是否有一种凝结的方法可以实现这一目标?
解决方案
您可以将其作为函数拔出:
Hook("first");
Hook("second");
function Hook( id )
{
$("#" + id + "_flip").hide();
$("#" + id + "_button_show").click(function(){
$("#" + id "_flip").animate({
opacity: 'toggle',
top: '+=524',
height: 'toggle'}, 600, function() {
// Animation complete.
});
});
$("#" + id + "_button_hide").click(function(){
$("#" + id + "_flip").animate({
opacity: 'toggle',
top: '-=524',
height: 'toggle'}, 400, function() {
// Animation complete.
});
});
}
甚至使函数都采用几个参数并循环循环。
不隶属于 StackOverflow