【问题标题】:Animate a div element changing its position in a div list为 div 元素设置动画,更改其在 div 列表中的位置
【发布时间】:2016-02-15 04:15:19
【问题描述】:

我正在尝试为 div 元素设置动画,因为它在排序的 div 列表中重新定位,因此它不会立即跳转,而是平滑过渡。列表数据来自 Mongo 集合,每个文档产生一个模板(一个 div 元素)。每个文档都有一个“投票”属性,列表根据该属性进行排序。登录的用户可以为每个帖子投票一次,如果帖子达到更高的点赞数,它会被重新定位。

我正在关注《发现流星》这本书,以防万一有人熟悉它。这是通过设置 CSS 过渡属性来处理的:transition: all 300ms 0ms ease-in;,在旧位置重新渲染帖子,然后在重新渲染后更改帖子的相对位置。后者当然是在 onRendered 函数中处理的。

这就是麻烦的开始。显然,一旦 div 元素获得足够的票数来改变其位置,onRendered 就不会触发。

所以,我的问题是:一旦列表重新排序,我如何为元素设置动画以改变其位置?

编辑:这是代码:

Template.postItem.onRendered(function(){
    //animate post from previous position to new position
    console.log(/*something so I know the onRendered function is firing*/);
    var instance = this;
    var rank = instance.data._rank;

    var $this = $(this.firstNode);
    var postHeight = 80;
    var newPosition = rank * postHeight;

    //if element has currentPosition (i.e. is not first ever rendered)
    if(typeof(instance.currentPosition)!=='undefined'){
        var previousPosition = instance.currentPosition;
        //calculate difference between old position and new position and send
        //element there
        var delta = previousPosition - newPosition;
        $this.css("top", delta + "px");
    }

    //let it draw in the old position, then...
    Meteor.defer(function(){
        instance.currentPosition = newPosition;
        //bring element back to its new original position
        $this.css("top", "0px");
    });
});

【问题讨论】:

  • 你的代码是……?

标签: javascript jquery css meteor


【解决方案1】:

我推荐使用 Blaze 的_uihooks。您可以注册一个钩子,当 Blaze 打算移动相应的 DOM 元素时将调用该钩子。

例如:

var hook = {
    moveElement: function(node, next) {
        var $node = $(node);
        /* Add animation code. */
        $node.animate();
    }
}

Template.postItem.onRendered(function() {
    /* Set hook to first node. */
    this.firstNode._uihooks = hook;
    /* Or to any other DOM element. */
    this.find('.postItem')._uihooks = hook;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2014-10-10
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多