鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ zepto如何監(jiān)聽元素的css變化?

zepto如何監(jiān)聽元素的css變化?

需要實(shí)時(shí)監(jiān)聽一個(gè)元素移動(dòng)時(shí)的實(shí)時(shí)的位置變化(變化是通過animate做的),并且在檢測(cè)到變化時(shí)處理一些事情,原生好像沒有這個(gè)樣的事件。
類似于 $(elem).on('elem_move',function(){});
在使用zepto.js前提下如何實(shí)現(xiàn)。

回答
編輯回答
來(lái)守候

zeptoanimate原理是給元素加css3transition過渡 或者 css3animation動(dòng)畫實(shí)現(xiàn)
這兩者只能監(jiān)聽動(dòng)畫結(jié)束時(shí)間無(wú)法監(jiān)聽運(yùn)動(dòng)過程
如果要獲取元素的實(shí)時(shí)位置可以用 setInterval 或者 setTimeout+遞歸 實(shí)現(xiàn)實(shí)時(shí)監(jiān)聽 間隔時(shí)間要把握好
簡(jiǎn)單的封裝:

;(function () {
    var timer = null;
    function listenMove() {
      var that = this;
      timer = setInterval(function () {
        that.trigger('elem_move');
      }, 0)
    }

    $.fn.myanimate = function (properties, duration, ease, callback, delay) {
      listenMove.call(this);
      return $(this).animate(properties, duration, ease, function () {
        clearInterval(timer);
        callback && callback.apply(this, arguments)
      }, delay)
    }
  })();
  
$(elem).myanimate({
  left: 1000
}, 5000);

$(elem).on("elem_move", function (e) {
  console.log(this)
});
2017年12月24日 21:06
編輯回答
雅痞

可以使用zepto的animate方法實(shí)現(xiàn)動(dòng)畫,可以監(jiān)聽動(dòng)畫完成時(shí)執(zhí)行回調(diào)函數(shù)
animate(properties, { duration: msec, easing: type, complete: fn })
如果想在元素變化過程中執(zhí)行回調(diào)函數(shù),使用setTimeout實(shí)現(xiàn)吧

2017年1月15日 18:23