一个网页多个 gridster.js 实例

在一个网页创建多个 gridster.js 实例的完整代码例子,gridster.js 通过 namespace 选项来确定 gridster.js 生成的CSS代码的范围。

完整代码

var gridster = [];
var serialization = [
  { row: 1, col: 1, size_x: 3, size_y: 1 },
  { row: 1, col: 4, size_x: 1, size_y: 1 },
  { row: 2, col: 1, size_x: 4, size_y: 1 },
];

var serialization2 = [
  { row: 1, col: 1, size_x: 3, size_y: 1 },
  { row: 1, col: 4, size_x: 1, size_y: 1 },
  { row: 2, col: 1, size_x: 4, size_y: 1 },
];

// sort serialization
serialization = Gridster.sort_by_row_and_col_asc(serialization);

$(function () {
  //初始化 gridster1 对象
  gridster[0] = $(".g1 ul").gridster({
    //用namespace区分
    namespace: '.g1',
    widget_base_dimensions: [150, 150],
    widget_margins: [5, 5],
    resize: {
      enabled: true
    }
  }).data('gridster');
  //初始化 gridster2 对象
  gridster[1] = $(".g2 ul").gridster({
    //用namespace区分
    namespace: '.g2',
    widget_base_dimensions: [150, 150],
    widget_margins: [5, 5],
    resize: {
      enabled: true
    }
  }).data('gridster')
  //第1个 gridster 容器
  $.each(serialization, function (index) {
    gridster[0].add_widget('<li>' + (index + 1) + '</li>', this.size_x, this.size_y, this.col, this.row);
  });
  //第2个 gridster 容器
  $.each(serialization2, function (index) {
    gridster[1].add_widget('<li>' + (index + 1) + '</li>', this.size_x, this.size_y, this.col, this.row);
  });

});

在线试一试