将按钮的背景图像设置为页面中已包含的元素

时间:2014-11-12 14:51:29

标签: javascript jquery html css

基本上我想使用图片网址之外的其他内容指定按钮的背景图片。能够将背景图像设置为DOM中包含的已加载元素将是理想的。这样我就可以在DOM中缓存加载gif(显示在按钮上),而不必在单击按钮时获取它。

我认为没有必要使用代码来说明问题,但无论如何都是一些

因点击图片加载而不理想:

    that.submitButtonSelector.css('background-image', 'url(/Content/_activity/ajax-loader.gif)');

理想(但没有明显的实现方式)

    that.submitButtonSelector.css('background-image', '#precachedImage');

2 个答案:

答案 0 :(得分:1)

如果您通过网址加载加载gif,则在大多数情况下都会缓存它。您只需要下载一次。之后,它将从缓存中提供。我唯一能想到的是使用base64源码。如果不生成HTTP请求,这会带来好处,但是当涉及到实际字节时,它会更大(我不认为较大的大小比另一个HTTP请求慢,但您可以始终对它们进行基准测试)。

根据我的经验,我相信base64图像非常棒,如果你需要立即显示加载图标,如果图标足够小,但如果你不需要立即显示,我建议通过url预加载图像javascript,只是依赖于缓存版本。

所以在你的情况下,如果你使用base64,你可以使用

that.submitButtonSelector.css('background-image', 'url(data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH+GkNyZWF0ZWQgd2l0aCBhamF4bG9hZC5pbmZvACH5BAAKAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQACgABACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkEAAoAAgAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkEAAoAAwAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw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e82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQACgAGACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAAKAAcALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==)
}

答案 1 :(得分:1)

您可以使用隐藏的div将图像预加载到缓存中,然后加载后可以添加背景。

HTML:

<img id="img" src="/Content/_activity/ajax-loader.gif" />

CSS:

#img {
    display: none;
}

jQuery的:

$("#img").load(function() {
    $(submitButtonSelector).click(function() {
        that.submitButtonSelector.css("background-image", "/Content/_activity/ajax-loader.gif");
    });
});