是否可以将一个元素还原为它's上一个位置,而不将该位置作为参数传递

Is it possible to restore an element to it's previous position without passing the position as a parameter?

本文关键字:位置 上一个 参数传递 是否 还原 元素 一个      更新时间:2023-09-26

以下函数采用options参数,并根据startValue:将元素动画化为特定的amount像素

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。)

您可以利用.animate()在调用时添加内联样式属性这一事实。因此,如果您想将元素恢复为CSS中指定的right值,可以调用.removeAttr("style")。要获得动画效果,您必须在CSS中包含一个transition属性。

例如,看看这个工作小提琴: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;
}

否则,据我所知,在调用.animate()之前,您需要获取并保存原始的right值。