Запустите функцию jQuery для каждого элемента в классе - PullRequest
0 голосов
/ 06 сентября 2011

У меня есть функция, которая изменяет размеры изображений на основе некоторых критериев и хотела бы, чтобы она вычисляла все элементы в классе .z по отдельности, а затем возвращала их.изображения через функцию, но возвращает одинаковые размеры для всех из них.Не уверен, где я облажался ...

Тестовый сайт находится здесь:

http://brantley.dhut.ch/

(также нужно договориться о сделке с появлением доразмер изображения был полностью изменен, но это будет другой вопрос)

JavaScript:

jQuery(function($) {
    $('.z').respond();
});

(function($){
    $.fn.respond = function() {

        /* initialize function on window load and resize */
        $(document).ready(function() {
            dimensions();
        });
        $(window).load(function() {     
            dimensions();
        });
        $(window).resize(function() {
            dimensions();
        });

        /* declare affected elements */
        var pic = this

        /* set image's height or width depending on the browser window's size */
        function dimensions() {
            return pic.each(function() {

            /* declare variables */
            var browserWidth = $(window).width();
            var imgRatio = pic.width() / pic.height()
            var availableHeight = ($(window).height() - $('header').height() - $('footer').height() - 80)
            var browserRatio = browserWidth / availableHeight

            /* image sizing logic */
            if (browserRatio >= imgRatio) {
                if (browserWidth > 640) {
                    /* if the browser is landscape and bigger than mobile, set the image's height to fill the available space */
                    pic.height(availableHeight).width('auto');
                    //$('body').css('background', 'blue');
                } else {
                    /* it's mobile */
                    pic.width(browserWidth - 40).height('auto');
                    //$('body').css('background', 'red');
                }
            } else {
                /* if the browser is portrait, set the image's width to fill the page */
                pic.width(browserWidth - 40).height('auto');
                //$('body').css('background', 'green');
            }

            /* horizontally center content */
            pic.css('margin-left', (browserWidth - pic.width())/2);

            });

        };

    };
})( jQuery );

Ответы [ 2 ]

1 голос
/ 06 сентября 2011

Вы используете pic.each() и внутри функции, которая должна вызываться для каждого элемента, выбранного объектом jquery «pic», вы также используете «pic». Попробуйте использовать this вместо этого:

return pic.each(function() {
        /* declare variables */
        var browserWidth = $(window).width();
        var imgRatio = $(this).width() / $(this).height()
0 голосов
/ 06 сентября 2011
function dimensions() {
            return pic.each(function() {

            /* declare variables */
            var browserWidth = $(window).width();
            var imgRatio = $(this).width() / $(this).height()
            var availableHeight = ($(window).height() - $('header').height() - $('footer').height() - 80)
            var browserRatio = browserWidth / availableHeight

            /* image sizing logic */
            if (browserRatio >= imgRatio) {
                if (browserWidth > 640) {
                    /* if the browser is landscape and bigger than mobile, set the image's height to fill the available space */
                    $(this).height(availableHeight).width('auto');
                    //$('body').css('background', 'blue');
                } else {
                    /* it's mobile */
                    $(this).width(browserWidth - 40).height('auto');
                    //$('body').css('background', 'red');
                }
            } else {
                /* if the browser is portrait, set the image's width to fill the page */
                $(this).width(browserWidth - 40).height('auto');
                //$('body').css('background', 'green');
            }

            /* horizontally center content */
            $(this).css('margin-left', (browserWidth - $(this).width())/2);

            });

        };
...