【问题标题】:Download and save a background image locally to use it offline in Ionic/Angularjs using imgcache.js使用 imgcache.js 在本地下载并保存背景图像以在 Ionic/Angularjs 中离线使用
【发布时间】:2015-10-23 05:53:40
【问题描述】:

我正在使用 imgcache.js 和自定义指令来下载图像并在本地保存以供离线使用。

库: https://github.com/chrisben/imgcache.js https://github.com/sunsus/ngImgCache/

情况是我需要将背景图像应用于内容(通常我们将背景图像应用于 .scroll-content 类)并且在 css 中我们不能使用指令或服务来保存文件本地。

我知道imgcache.js库有一个名为:ImgCache.cacheBackground()的函数,但我不知道如何使用它并将本地文件应用到.scroll-content。

请问,有什么帮助吗?有什么例子吗?

【问题讨论】:

  • 你能接受你自己的答案吗?

标签: javascript angularjs caching ionic-framework offline-mode


【解决方案1】:

我找到了一种实现缓存的方法:https://github.com/chrisben/imgcache.js

我已将图像应用到 .scroll-content:

.scroll-content{
    background-image: url(http://test.com/background.jpg);
}

并创建了一个指令:

.directive('cacheBackground', function($timeout) {
return {
restrict: 'A',
link: function(scope, el, attrs) {      
    // timeout to give time to init imgCache
    $timeout(function() {
        ImgCache.isBackgroundCached(el, function(path, success) {
            if (success) {
                ImgCache.useCachedBackground(el);
            } else { 
                ImgCache.cacheBackground(el, function() {
                    ImgCache.useCachedBackground(el);
                });
            }
        });
    }, 200);
}
};
})

修改了 imgCache.js 中的 DomHelpers.getBackgroundImage 以使用 getComputedStyle,即使我们有 jQueryLite:

DomHelpers.getBackgroundImage = function (element) {

if (ImgCache.jQuery) {
    return element.attr('data-old-background') ? "url(" + element.attr('data-old-background') + ")" : element.css('background-image');
} else if (ImgCache.jQueryLite) {

    var style = window.getComputedStyle(element[0], null);
    if (!style) {
        return;
    }
    return element[0].getAttribute("data-old-background") ? "url(" + element[0].getAttribute("data-old-background") + ")" : style.backgroundImage;

} else {
    var style = window.getComputedStyle(element, null);
    if (!style) {
        return;
    }
    return element.getAttribute("data-old-background") ? "url(" + element.getAttribute("data-old-background") + ")" : style.backgroundImage;
}
};

然后在我看来,我将该指令应用于 ion-content:

现在背景图片也可以离线工作了。

谢谢!

【讨论】:

    猜你喜欢
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多