首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自动化jquery滑块

自动化jquery滑块
EN

Stack Overflow用户
提问于 2012-04-22 19:26:16
回答 2查看 116关注 0票数 1

我有这个例子:Click!

使用以下jquery:

代码语言:javascript
复制
$(".abox-1").click(function(){
    $("#box-2, #box-3").css({
        zIndex: "-999"
    });
    $("#box-1").css({
        zIndex: "999"
    });
    $("#box-1").stop().animate({
        top: "0%"
    }, 1000, "easeInOutExpo");
    $("#box-2, #box-3").stop().delay(1000).animate({
        top: "100%"
    });
});
$(".abox-2").click(function(){
    $("#box-2").css({
        zIndex: "999"
    });
    $("#box-2").stop().animate({
        top: "0%"
    }, 1000, "easeInOutExpo");
    $("#box-1, #box-3").css({
        zIndex: "-999"
    });
    $("#box-1, #box-3").stop().delay(1000).animate({
        top: "100%"
    });
});
$(".abox-3").click(function(){
    $("#box-1, #box-2").css({
        zIndex: "-999"
    });
    $("#box-3").css({
        zIndex: "999"
    });
    $("#box-3").stop().animate({
        top: "0%"
    }, 1000, "easeInOutExpo");
    $("#box-2, #box-1").stop().delay(1000).animate({
        top: "100%"
    });
});

但是,正如您所看到的,这是非常丑陋的代码!并且占用了大量的空间。我怎么才能把它变成一个函数呢?或者我如何缩短代码?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-22 19:53:51

您应该将abox-i类更改为ids aboxi,并使用以下代码:

代码语言:javascript
复制
function show_box(number) {
  for(var i = 1; i <= 3; i++) {
    if (i == number) { // we need to show this element
      $("#box-" + i).css({
        zIndex: "999"
      }).stop().animate({
        top: "0%"
      }, 1000, "easeInOutExpo");
    } else { // we need to hide this element
      $("#box-"+i).css({
        zIndex: "-999"
      }).stop().delay(1000).animate({
        top: "100%"
      });
    }
  }
}

$("#nav a").click(function() {
  var id = parseInt(this.id.substr(4));
  if (id > 0) show_box(id);   
});

JsFiddle

票数 1
EN

Stack Overflow用户

发布于 2012-04-22 20:04:25

也许是这样的?

代码语言:javascript
复制
$(document).ready(function(){
    $('a[class^="abox"]').click(function() {
        if (this.className == 'abox') {
            $('div[id^=box-]').animate({top: '100%'}, 1000, "easeInOutExpo").css({zIndex: "-999"});
        }else{
            var thisbox = $('#'+this.className.replace('a', '')),
                otherbox = $('div[id^=box-]').not(thisbox);

            otherbox.css({zIndex: "-999"}).stop().delay(1000).animate({top: '100%'});
            thisbox.css({zIndex: "999"}).stop().animate({top: '0%'}, 1000, "easeInOutExpo");
        }
    });
});

FIDDLE

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10267531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档