Cambiar el tamaño de jqGrid cuando se cambia el tamaño del navegador?
-
22-08-2019 - |
Solución 2
Como seguimiento:
El código anterior se muestra en este post fue abandonado porque era poco fiable. Ahora estoy usando la siguiente función API para cambiar el tamaño de la red, como se recomienda en la documentación jqGrid:
jQuery("#targetGrid").setGridWidth(width);
Para hacer el cambio de tamaño, una función de la aplicación de la siguiente lógica está obligado a eventos de cambio de tamaño de la ventana:
-
Calcular la anchura de la rejilla usando clientWidth y de su padre (si no es disponible) su atributo offsetWidth.
-
Realizar una comprobación de validez para asegurarse de que la anchura ha cambiado más de x píxeles (para evitar algunos problemas específicos de la aplicación)
-
Finalmente, utilice setGridWidth () para cambiar el ancho de la rejilla
Aquí es código de ejemplo para manejar el cambio de tamaño:
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');
Y el ejemplo de marcado:
<div id="grid_container">
<table id="grid"></table>
<div id="grid_pgr"></div>
</div>
Otros consejos
Estado usando esto en producción desde hace algún tiempo y sin ninguna queja (puede tardar algunos ajustes a mirar a la derecha en su sitio .. por ejemplo, restando la anchura de una barra lateral, etc)
$(window).bind('resize', function() {
$("#jqgrid").setGridWidth($(window).width());
}).trigger('resize');
cambio de tamaño automático:
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);
});
}
}
Esto parece estar funcionando muy bien para mí
$(window).bind('resize', function() {
jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');
Estoy usando 960.gs para la disposición así que mi solución es la siguiente:
$(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"
}
});
// Otras redes se definen a continuación ...
Préstamos a partir del código en su enlace podría intentar algo como esto:
$(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%');
});
});
Esta forma en que está uniéndose directamente al evento window.onresize, que en realidad se parece a lo que quiere de su pregunta.
Si su red se establece en 100% de ancho aunque debería ampliar automáticamente cuando el envase se expande, a menos que haya algunas complejidades al plugin que está utilizando que yo no conozco.
Si:
- tener
shrinkToFit: false
(media columnas de ancho fijo) - Tienes
autowidth: true
- no se preocupan por la altura de líquido
- tienen barra de desplazamiento horizontal
Usted puede hacer la red con ancho de fluido con estilos siguientes:
.ui-jqgrid {
max-width: 100% !important;
width: auto !important;
}
.ui-jqgrid-view,
.ui-jqgrid-hdiv,
.ui-jqgrid-bdiv {
width: auto !important;
}
La respuesta principal trabajó para mí, pero hizo la aplicación extremadamente insensible en IE, así que utiliza un temporizador como se sugiere. Código ve algo como esto ($(#contentColumn)
es el div que el jqGrid se sienta en):
function resizeGrids() {
var reportObjectsGrid = $("#ReportObjectsGrid");
reportObjectsGrid.setGridWidth($("#contentColumn").width());
};
var resizeTimer;
$(window).bind('resize', function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeGrids, 60);
});
Hola entusiastas de desbordamiento de pila. Me gustó la mayoría de las respuestas, e incluso me up-votado en una pareja, pero ninguno de ellos trabajó para mí en IE 8 por alguna extraña razón ... sin embargo, me he corrido en estos enlaces ... Este hombre escribió una biblioteca que parece trabajo. Incluirlo en sus proyectos en adittion a jQuery UI, el tiro en el nombre de la tabla y el div.
http: // stevenharman. net / blog / archivo / 2009/08/21 / creación-a-fluido-jquery-jqgrid.aspx
autowidth: true
funcionaba perfectamente para mí. aprendido de aquí .
Esto 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>