【问题标题】:Find if the value increased or decreased last time it changed查找上次更改时值是增加还是减少
【发布时间】:2018-07-09 23:28:54
【问题描述】:

我正在上下拖动一个元素,我希望它根据其属性变化来做特定的事情。我需要知道它的“顶部”属性的值自上次更改以来是增加还是减少。怎么做?

header.draggable({
    axis: 'y',
    containment: [0, 0, 0, '800px'],
    stop: function () {
        if (header.css('top') > '200px' && header.css('top') != 'auto') {
            header.animate({
                top: '800px'
            }, 1000);
            $('.nav').addClass('nav--active');
            $('.nav__wrapper').addClass('nav__wrapper--active');
            $('.nav__item').addClass('nav__item--active');
            $('.header__wrapper').addClass('header__wrapper--active');
        } else {
            header.animate({
                top: '0px'
            }, 500);
            $('.nav').removeClass('nav--active');
            $('.nav__wrapper').removeClass('nav__wrapper--active');
            $('.nav__item').removeClass('nav__item--active');
            $('.header__wrapper').removeClass('header__wrapper--active');
        }
    },
});

我正在使用 jQuery UI Draggable 来拖动标题,如果我向上拖动它,我希望它到顶部,如果我向下拖动它,我希望它设置 top = 800px。

【问题讨论】:

  • 请发布您的代码并提供更多信息。

标签: javascript jquery html jquery-ui draggable


【解决方案1】:

使用两个变量yStartyStopui.offset.top 存储在可拖动的start: 和可拖动的stop: 事件中

$("#dragHandle").draggable({
  axis: "y",
  containment: "parent",
  start: function(ev, ui) {
    this.yStart = ui.offset.top;
  },
  stop: function(ev, ui) {
    this.yStop = ui.offset.top;
    
    var px = this.yStop - this.yStart;
    if (px === 0) {
      console.log("Not moved");
    } else if (px > 0) {
      console.log("Moved Down by " + Math.abs(px) + "px");
    } else {
      console.log("Moved Up by " + Math.abs(px) + "px");
    }
  }
});
#dragWrapper {
  background: #ddd;
  position: relative;
  width: 30px;
  height: 100px;
}

#dragHandle {
  background: chocolate;
  position: absolute;
  top: 0;
  width: 30px;
  height: 30px;
}
<div id="dragWrapper">
  <div id="dragHandle"></div>
</div>

<script src="//code.jquery.com/jquery-3.1.0.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

【讨论】:

    【解决方案2】:

    你可以给元素添加一个属性,例如 &lt;div number="0"&gt; &lt;/div&gt;,每次拖动它都会更改该数字&lt;div number="2"&gt;,然后将其与最后一个数字进行比较,看看是更大还是更小。 (你在改变之前比较)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2020-03-08
      • 2021-10-24
      • 2017-11-16
      • 1970-01-01
      • 2019-09-03
      相关资源
      最近更新 更多