如何选择页面中的所有图像?

时间:2012-06-27 06:31:24

标签: javascript iphone ipad resolution retina-display

我有这个jQuery脚本,可以为任何标记为data-retina="true" retina-resolution-imagebackground-image的图像或对象提供。

但是如何从脚本中删除最后一部分,以便此功能适用于每个图像,而不仅仅是data-retina标记的图像?

 (function($) {
    "use strict";

    var retinaReplace = function(element, options) {

        this.options = options;
        var $el = $(element);
        var is_image = $el.is('img');
        var normal_url = is_image ? $el.attr('src') : $el.backgroundImageUrl();
        var retina_url = this.options.generateUrl($el, normal_url);

        $('<img/>').attr('src', retina_url).load(function() {

            if (is_image) {
                $el.attr('src', $(this).attr('src'));
            } else {
                $el.backgroundImageUrl($(this).attr('src'));
                $el.backgroundSize($(this)[0].width, $(this)[0].height);
            }

            $el.attr('data-retina', 'complete');
        });
    }

    retinaReplace.prototype = {
        constructor: retinaReplace
    }

    $.fn.retinaReplace = function(option) {

        if (getDevicePixelRatio() <= 1) { return this; }

        return this.each(function() {
            var $this = $(this);
            var data = $this.data('retinaReplace');
            var options = $.extend({}, $.fn.retinaReplace.defaults, $this.data(), typeof option == 'object' && option);
            if (!data) { $this.data('retinaReplace', (data = new retinaReplace(this, options))); }
            if (typeof option == 'string') { data[option](); }
        });
    }

    $.fn.retinaReplace.defaults = {
        suffix: '-x2', 
        generateUrl: function(element, url) {
            var dot_index = url.lastIndexOf('.');
            var extension = url.substr(dot_index + 1);
            var file = url.substr(0, dot_index);
            return file + this.suffix + '.' + extension;
        }
    }

    $.fn.retinaReplace.Constructor = retinaReplace;

    var getDevicePixelRatio = function() {
        if (window.devicePixelRatio === undefined) { return 1; }
        return window.devicePixelRatio;
    }

    $.fn.backgroundImageUrl = function(url) {
        return url ? this.each(function () { 
            $(this).css("background-image", 'url("' + url + '")')
        }) : $(this).css("background-image").replace(/url\(|\)|"|'/g, "");
    }

    $.fn.backgroundSize = function(retinaWidth, retinaHeight) {
        var sizeValue = Math.floor(retinaWidth/2) + 'px ' + Math.floor(retinaHeight/2) + 'px';
        $(this).css("background-size", sizeValue);
        $(this).css("-webkit-background-size", sizeValue);
    }

    $(function(){
        $("[data-retina='true']").retinaReplace();
    });

})(window.jQuery);

1 个答案:

答案 0 :(得分:2)

  

如何从脚本中删除最后一部分,以便此功能适用于每个图像,而不仅仅是使用data-retina-tag的一次?

更改:

$(function(){
    $("[data-retina='true']").retinaReplace();
});

$(function(){
    $("img").retinaReplace();
});