当图像src绑定发生变化时,knockout js淡出过渡绑定处理程序

时间:2013-06-15 08:00:50

标签: binding knockout.js bindinghandlers

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

.js(viewModel):

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

视图:

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

如何创建一个ko绑定处理程序,在图像属性发生变化时执行简单的交叉渐变?

1 个答案:

答案 0 :(得分:3)

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

这是一个简单的绑定处理程序,每次更新源可观察对象时,它都会在绑定元素中创建一个新图像(或者在这种情况下带有背景图像的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即可轻松替换更复杂的动画,例如滑动。

Here is a fiddle for it!