2016-04-15 20 views
1

下面的函數需要一個options參數和動畫元素,基於像素的特定amount一個startValue是否有可能將元素恢復到之前的位置,而不將該位置作爲參數傳遞?

options: { 
    property: 'right', 
    startValue: '-250px', 
    amount: '250px' 
}, 

function (options) { 
    const $el = $(this.el) 
    $el.click(() => { 
    const startValue = $el.parent().css(slide.property) 
    const calcValue = parseInt(startValue, 10) + parseInt(slide.amount, 10) 
    if (startValue === slide.startValue) { 
     $el.parent().animate({ [slide.property]: calcValue }, 200) 
    } else { 
     $el.parent().animate({ [slide.property]: slide.startValue }, 200) 
    } 
    }) 
} 

但我不知道,是有可能實現相同的,而無需提供startValue的功能? (例如如果right初值爲0然後將其還原到0你第二次單擊該元素。)

+0

恢復到以前的位置是什麼意思? – digglemister

+0

@snookieordie我在問題中澄清了這一點。 – alexchenco

回答

1

你可以採取的事實.animate()被添加內嵌樣式屬性,當它被稱爲優勢。因此,如果您想將元素恢復到CSS中指定的right值,您可以撥打.removeAttr("style")。要獲得動畫效果,您必須在CSS中包含轉場屬性。

例如,看看這個工作提琴:https://jsfiddle.net/hr0cxax2/1/

$("#slideButton").on("click", function() { 
    $("div").animate({right:"-=50px"}, 200); 
}); 

$("#restoreButton").on("click", function() { 
    $("div").removeAttr("style"); 
}); 

div { 
    height: 50px; 
    width: 50px; 
    top: 20px; 
    right: 300px; 
    background-color: red; 
    position: fixed; 
    -webkit-transition: right 0.2s; 
    -moz-transition: right 0.2s; 
    transition: right 0.2s; 
} 

另外,據我所知,你將需要獲得並保存原始right.animate()被稱爲前。

相關問題