我有两个类似的功能,如下所示;
对于最后一个元素函数;
function last () {
var $this = $(this);
$this.animate({
left:'-1200',
opacity:0
},500, function(){
$this
.addClass('hide')
.next()
.removeClass('hide').animate({
left:'0',
opacity:1
},500)
});
}
对于第一个元素函数;
function first () {
var $this = $(this);
$this.animate({
left:'1200',
opacity:0
},500, function(){
$this
.addClass('hide')
.prev()
.removeClass('hide').animate({
left:'0',
opacity:1
},500)
});
}
它们很相似,我想将它们组合为一个功能,如下所示;
function steps (pos) { /* -- Dif-1 -- */
var $this = $(this);
$this.animate({
left:pos==='next'&& '-'+'1200', /* -- Dif-2 -- */
opacity:0
},500, function(){
$this
.addClass('hide')
pos==='next' ? next() : prev() /* -- Dif-3 -- */
.removeClass('hide').animate({
left:'0',
opacity:1
},500)
});
}
我想根据pos变量(pos ==='next'?next():prev())确定函数next()或prev()。我怎样才能做到这一点?
您left
可以使用简单的三元运算符来完成属性的区别:
left: pos==='next' ? -1200 : 1200
如果您使用方括号表示法来调用prev()
或,则可以继续链接方法next()
:
$this.addClass('hide')
[pos==='next' ? "next" : "prev"]()
.removeClass('hide').animate({
或者,假设pos
将始终为next
或prev
,只需使用[pos]()
:
function steps (pos) {
var $this = $(this);
$this.animate({
left:pos==='next' ? -1200 : 1200,
opacity:0
},500, function(){
$this
.addClass('hide')[pos]()
.removeClass('hide').animate({
left:'0',
opacity:1
},500)
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句