Карта местности во вкладке начальной загрузки не работает - PullRequest
0 голосов
/ 30 октября 2018

У меня есть вкладки начальной загрузки, которые работают хорошо. У меня есть карта местности, которая работает хорошо, если она не вставлена ​​во вкладку. Я использую jQuery плагин Responsive Image Maps от Мэтта Стоу, тоже отлично работает.

Симптом: Затем я поместил карту местности в одну из вкладок, по умолчанию не активную. Затем я нажимаю на вкладку, чтобы она отображалась. Так что img хорошо показано. Но карта местности не работает. Я не вижу кликабельный прямоугольник. Но если я вручную изменю размер своего навигатора, то карта местности будет работать.

Страница: https://boutique.bilp.fr/71-les-pieds-de-poteaux.html Выберите вкладку «Guide de choix», белые прямоугольники должны быть кликабельными. Этого нет, пока я вручную не изменю размер окна.

Причина: Ответственным за это является плагин Responsive Image Maps jQuery. В своем коде он вызывает метод jquery .width (), чтобы получить ширину img, где должна работать карта. А поскольку родитель (вкладка) скрыт, возвращаемая ширина неверна. И он использует это, чтобы изменить размер карты ... с плохими значениями. Тогда карта настолько мала, что кажется, что она не работает.

Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 30 октября 2018

Одним из решений является изменение jQuery-плагина Responsive Image Maps, сделав предков видимыми перед вызовом width ().

Оригинальный код:

/*
* rwdImageMaps jQuery plugin v1.6
*
* Allows image maps to be used in a responsive design by     recalculating the area coordinates to match the actual image size on load and window.resize
*
* Copyright (c) 2016 Matt Stow
* https://github.com/stowball/jQuery-rwdImageMaps
* http://mattstow.com
* Licensed under the MIT license
*/
;(function($) {
$.fn.rwdImageMaps = function() {
    var $img = this;

    var rwdImageMap = function() {
        $img.each(function() {
            if (typeof($(this).attr('usemap')) == 'undefined')
                return;

            var that = this,
                $that = $(that);

            // Since WebKit doesn't know the height until after the image has loaded, perform everything in an onload copy
            $('<img />').on('load', function() {
                var attrW = 'width',
                    attrH = 'height',
                    w = $that.attr(attrW),
                    h = $that.attr(attrH);

                if (!w || !h) {
                    var temp = new Image();
                    temp.src = $that.attr('src');
                    if (!w)
                        w = temp.width;
                    if (!h)
                        h = temp.height;
                }

                var wPercent = $that.width()/100,
                    hPercent = $that.height()/100,
                    map = $that.attr('usemap').replace('#', ''),
                    c = 'coords';

                $('map[name="' + map + '"]').find('area').each(function() {
                    var $this = $(this);
                    if (!$this.data(c))
                        $this.data(c, $this.attr(c));

                    var coords = $this.data(c).split(','),
                        coordsPercent = new Array(coords.length);

                    for (var i = 0; i < coordsPercent.length; ++i) {
                        if (i % 2 === 0)
                            coordsPercent[i] = parseInt(((coords[i]/w)*100)*wPercent);
                        else
                            coordsPercent[i] = parseInt(((coords[i]/h)*100)*hPercent);
                    }
                    $this.attr(c, coordsPercent.toString());
                });
            }).attr('src', $that.attr('src'));
        });
    };
    $(window).resize(rwdImageMap).trigger('resize');

    return this;
};
})(jQuery);

Модифицированный код:

/*
* rwdImageMaps jQuery plugin v1.6
*
* Allows image maps to be used in a responsive design by recalculating the area coordinates to match the actual image size on load and window.resize
*
* Copyright (c) 2016 Matt Stow
* https://github.com/stowball/jQuery-rwdImageMaps
* http://mattstow.com
* Licensed under the MIT license
*/
;(function($) {
$.fn.rwdImageMaps = function() {
    var $img = this;

    var rwdImageMap = function() {

        $img.each(function() {
            if (typeof($(this).attr('usemap')) == 'undefined')
                return;

            var that = this,
                $that = $(that);

                // Since WebKit doesn't know the height until after the image has loaded, perform everything in an onload copy
            $('<img />').on('load', function() {

                // Modif BC : make ancestors visible so .width() can return the right value
                //************************************************
                var hidden_ancestors = [];
                $that.parents().each(function() {
                    if ($(this).css('display') == 'none')
                    {

                $(this).show();
                        hidden_ancestors.push($(this));
                    };
                });
                // END Modif BC

                var attrW = 'width',
                    attrH = 'height',
                    w = $that.attr(attrW),
                    h = $that.attr(attrH);

                if (!w || !h) {
                    var temp = new Image();
                    temp.src = $that.attr('src');
                    if (!w)
                        w = temp.width;
                    if (!h)
                        h = temp.height;
                }

                var wPercent = $that.width()/100,
                    hPercent = $that.height()/100,
                    map = $that.attr('usemap').replace('#', ''),
                    c = 'coords';

                $('map[name="' + map + '"]').find('area').each(function() {
                    var $this = $(this);
                    if (!$this.data(c))
                        $this.data(c, $this.attr(c));

                    var coords = $this.data(c).split(','),
                        coordsPercent = new Array(coords.length);

                    for (var i = 0; i < coordsPercent.length; ++i) {
                        if (i % 2 === 0)
                            coordsPercent[i] = parseInt(((coords[i]/w)*100)*wPercent);
                        else
                            coordsPercent[i] = parseInt(((coords[i]/h)*100)*hPercent);
                    }
                    $this.attr(c, coordsPercent.toString());
                });


                // Modif BC : Restore invisibility on ancestors
                //*********************************************
                jQuery.each(hidden_ancestors, function(index, value)
                {
                    $(value).css({display: ''});
                });
                // END Modif BC

            }).attr('src', $that.attr('src'));
        });
    };
    $(window).resize(rwdImageMap).trigger('resize');

    return this;
};
})(jQuery);

Я предложу это усовершенствование Мэтту Стоу, автору

...