当图像SRC绑定改变时,Knockout js fade transition绑定处理程序



如果我有以下简单的js/knockout代码:

. js (viewModel):

var image = ko.observable('http://placehold.it/300x150');

视图:

<img data-bind={attr: {src: image}} />

我如何创建一个ko绑定处理程序,将执行一个简单的交叉淡出时,图像属性的变化?

我认为最好的解决方案是创建另一个图像并将其淡入。

下面是一个简单的绑定处理程序,它将在每次源可观察对象更新时在绑定元素中创建一个新图像(在本例中是带有背景图像的div),并使用CSS3动画淡出:

ko.bindingHandlers.transitionImage = {
    init: function (element, valueAccessor) {
        // create a holder for the images
        var holder = document.createElement('div');
        holder.style['position'] = 'relative';
        holder.style['height'] = '100%';
        holder.style['width'] = '100%';
        element.appendChild(holder);
        // create initial image
        var url = ko.utils.unwrapObservable(valueAccessor());
        var fore = document.createElement('div');
        fore.style['background-image'] = 'url(' + url + ')';
        fore.style['position'] = 'absolute';
        fore.style['height'] = '100%';
        fore.style['width'] = '100%';
        fore.style['background-size'] = '100% 100%'
        holder.appendChild(fore);
    },
    update: function (element, valueAccessor) {
        var url = ko.utils.unwrapObservable(valueAccessor());
        // retrieve the holder element
        var holder = element.childNodes[0];
        // create new image to transition to
        var fore = document.createElement('div');
        fore.className = 'transition';
        fore.style['background-image'] = 'url(' + url + ')';
        fore.style['position'] = 'absolute';
        fore.style['height'] = '100%';
        fore.style['width'] = '100%';
        fore.style['background-size'] = '100% 100%'
        fore.style['opacity'] = '0'; // ensure it is hidden
        holder.appendChild(fore);
        // CSS3 animate opacity
        setTimeout(function () {
            fore.style['opacity'] = '1';
        }, 0);
        // dispose of unnecessary hidden images eventually
        setTimeout(function () {
            var toRemove = holder.childNodes[0];
            var removed = holder.removeChild(toRemove);
            delete removed;
        }, 10000);
    }
};

它需要一些css来让不透明度变得生动:

div.transition {
    -webkit-transition: opacity 0.5s linear;
    -moz-transition: opacity 0.5s linear;
    -o-transition: opacity 0.5s linear;
    transition: opacity 0.5s linear;
}

使用时,将其绑定到div容器:

<div data-bind="transitionImage: image" style="width: 100px; height: 100px"></div>

这种方法的优点是,它很容易替代更复杂的动画,如滑动,只需玩css。

给你一把小提琴!

相关内容

  • 没有找到相关文章

最新更新