1

我有这个 jQuery 脚本,它提供任何带有标签data-retina="true"aretina-resolution-image或的图像或对象background-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);
4

1 回答 1

2

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

改变:

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

至:

$(function(){
    $("img").retinaReplace();
});
于 2012-06-27T06:33:02.157 回答