Pergunta

Existe alguma maneira para redimensionar um jqGrid quando a janela do navegador é redimensionada? Eu tentei o método descrito aqui mas essa técnica não funciona no IE7.

Foi útil?

Solução 2

Como um follow-up:

O código anterior mostrado neste post acabou por ser abandonada porque não era confiável. Agora estou usando a seguinte função API para redimensionar a grade, como recomendado pela documentação jqGrid:

jQuery("#targetGrid").setGridWidth(width);

Para fazer o redimensionamento real, uma função de implementar a seguinte lógica é obrigado a evento de redimensionamento da janela:

  • Calcular a largura da grade usando clientWidth e do seu pai (se é que não está disponível) seu atributo offsetWidth.

  • Executar uma verificação de sanidade para se certificar de largura mudou mais do que x pixels (Para contornar alguns problemas específicos do aplicativo)

  • Finalmente, o uso setGridWidth () para alterar a grade de largura

Aqui é exemplo de código a alça de redimensionamento:

jQuery(window).bind('resize', function() {

    // Get width of parent container
    var width = jQuery(targetContainer).attr('clientWidth');
    if (width == null || width < 1){
        // For IE, revert to offsetWidth if necessary
        width = jQuery(targetContainer).attr('offsetWidth');
    }
    width = width - 2; // Fudge factor to prevent horizontal scrollbars
    if (width > 0 &&
        // Only resize if new width exceeds a minimal threshold
        // Fixes IE issue with in-place resizing when mousing-over frame bars
        Math.abs(width - jQuery(targetGrid).width()) > 5)
    {
        jQuery(targetGrid).setGridWidth(width);
    }

}).trigger('resize');

E exemplo de marcação:

<div id="grid_container">
    <table id="grid"></table>
    <div id="grid_pgr"></div>
</div>

Outras dicas

vindo a utilizar este em produção há algum tempo sem quaisquer queixas (pode demorar alguns ajustes para olhar direito em seu site .. por exemplo, subtraindo a largura de uma barra lateral, etc)

$(window).bind('resize', function() {
    $("#jqgrid").setGridWidth($(window).width());
}).trigger('resize');

Auto redimensionamento:

Para JQGrid 3,5 +

        if (grid = $('.ui-jqgrid-btable:visible')) {
            grid.each(function(index) {
                gridId = $(this).attr('id');
                gridParentWidth = $('#gbox_' + gridId).parent().width();
                $('#' + gridId).setGridWidth(gridParentWidth);
            });
        }

Para jqgrid 3.4.x:

       if (typeof $('table.scroll').setGridWidth == 'function') {
            $('table.scroll').setGridWidth(100, true); //reset when grid is wider than container (div)
            if (gridObj) {

            } else {
                $('#contentBox_content .grid_bdiv:reallyvisible').each(function(index) {
                    grid = $(this).children('table.scroll');
                    gridParentWidth = $(this).parent().width() – origami.grid.gridFromRight;
                    grid.setGridWidth(gridParentWidth, true);
                });
            }
        }

este parece estar funcionando bem para mim

$(window).bind('resize', function() {
    jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');

Eu estou usando 960.gs de layout para a minha solução é a seguinte:

    $(window).bind(
        'resize',
        function() {
                    //  Grid ids we are using
            $("#demogr, #allergygr, #problemsgr, #diagnosesgr, #medicalhisgr").setGridWidth(
                    $(".grid_5").width());
            $("#clinteamgr, #procedgr").setGridWidth(
                    $(".grid_10").width());
        }).trigger('resize');
// Here we set a global options

jQuery.extend(jQuery.jgrid.defaults, {
    // altRows:true,
    autowidth : true,
    beforeSelectRow : function(rowid, e) { // disable row highlighting onclick
        return false;
    },
    datatype : "jsonstring",
    datastr : grdata,  //  JSON object generated by another function
    gridview : false,
    height : '100%',
    hoverrows : false,
    loadonce : true,
    sortable : false,
    jsonReader : {
        repeatitems : false
    }
});

// Demographics Grid

$("#demogr").jqGrid( {
    caption : "Demographics",
    colNames : [ 'Info', 'Data' ],
    colModel : [ {
        name : 'Info',
        width : "30%",
        sortable : false,
        jsonmap : 'ITEM'
    }, {
        name : 'Description',
        width : "70%",
        sortable : false,
        jsonmap : 'DESCRIPTION'
    } ],
    jsonReader : {
        root : "DEMOGRAPHICS",
        id : "DEMOID"
    }
});

// Outras redes definido abaixo ...

O empréstimo do código em seu link, você pode tentar algo como isto:

$(window).bind('resize', function() { 
    // resize the datagrid to fit the page properly:
    $('div.subject').children('div').each(function() {
        $(this).width('auto');
        $(this).find('table').width('100%');
    });
});

Desta forma você está ligando-se diretamente para o evento window.onresize, que realmente se parece com o que você quer da sua pergunta.

Se a sua rede está definido para 100% de largura embora deva se expandir automaticamente quando seus expande recipiente, a menos que há algumas complexidades para o plugin que você está usando que eu não sei sobre.

Se você:

  • ter shrinkToFit: false (média de largura fixa colunas)
  • Have autowidth: true
  • não se preocupam com altura fluido
  • Have horizontal barra de rolagem

Você pode fazer grade com largura de fluido com as seguintes estilos:

.ui-jqgrid {
  max-width: 100% !important;
  width: auto !important;
}

.ui-jqgrid-view,
.ui-jqgrid-hdiv,
.ui-jqgrid-bdiv {
   width: auto !important;
}

Aqui está uma demonstração

A resposta principal trabalhou para mim, mas fez o aplicativo extremamente insensível no IE, então eu usei um temporizador como sugerido. Código é algo como isto ($(#contentColumn) é o div que o JQGrid senta em):

  function resizeGrids() {
    var reportObjectsGrid = $("#ReportObjectsGrid");
    reportObjectsGrid.setGridWidth($("#contentColumn").width());
};

var resizeTimer;

$(window).bind('resize', function () {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resizeGrids, 60);
});

Olá Pilha entusiastas transbordar. I ditou o ritmo de respostas, e eu mesmo up-votado um casal, mas nenhum deles funcionou para mim no IE 8, por algum motivo estranho ... Eu fiz no entanto correr para esses links ... Esse cara escreveu uma biblioteca que parece trabalhos. Incluí-lo em seus projetos em adittion a UI do jQuery, jogue em nome de sua mesa e a div.

http: // stevenharman. net / blog / Arquivo / 2009/08/21 / criando-a-fluido-jquery-jqgrid.aspx

http://code.google.com/p/codeincubator/source/browse/#svn%2FSamples%2Fsteveharman%2FjQuery%2Fjquery.jqgrid.fluid%253Fstate%253Dclosed

autowidth: true

funcionou perfeitamente para mim. aprendido com aqui .

Isso funciona ..

var $targetGrid = $("#myGridId");
$(window).resize(function () {
    var jqGridWrapperId = "#gbox_" + $targetGrid.attr('id') //here be dragons, this is     generated by jqGrid.
    $targetGrid.setGridWidth($(jqGridWrapperId).parent().width()); //perhaps add padding calculation here?
});
<script>
$(document).ready(function(){    
$(window).on('resize', function() {
    jQuery("#grid").setGridWidth($('#fill').width(), false); 
    jQuery("#grid").setGridHeight($('#fill').height(),true); 
}).trigger('resize');      
});
</script>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top