1

我添加了 10 个可拖动的矩形,我希望能够在它们被一个一个单击时将它们删除。现在它只删除第一个,然后不再删除。是否可以向矩形 ID 添加点击事件?

http://jsfiddle.net/dmYbA/

var stage = new Kinetic.Stage({
    container: 'container',
    width: 578,
    height: 400
  });

  var layer = new Kinetic.Layer();

for (var i = 0; i< 10; i++) {

  var rect = new Kinetic.Rect({
    x: 239 + (i *3),
    y: 75 + (i * 3),
    width: 100,
    height: 50,
    fill: 'blue',
    stroke: 'black',
    strokeWidth: 4,
      draggable: true,
      id: i
  });

rect.on('click', function() {
   rect.hide();

});

  // add the shape to the layer
  layer.add(rect);

  // add the layer to the stage
  stage.add(layer);
}
4

1 回答 1

1

为了能够一次删除每个矩形,我首先将新层移动到 for 循环内。我还添加了一个组,每个矩形都添加到其中。然后在 rect.on 内部将其设置为 this.remove() 而不是 rect.remove()。

http://jsfiddle.net/DP53S/

var stage = new Kinetic.Stage({
    container: 'container',
    width: 578,
    height: 400
  });



for (var i = 0; i< 10; i++) {
   var group = new Kinetic.Group({
    draggable: true
});
  var layer = new Kinetic.Layer();
  var rect = new Kinetic.Rect({
    x: 239 + (i *3),
    y: 75 + (i * 3),
    width: 100,
    height: 50,
    fill: 'blue',
    stroke: 'black',
    strokeWidth: 4
  });

rect.on('click', function() {
   this.remove();
   layer.draw();

});

  // add the shape to the layer
  group.add(rect)
  layer.add(group);

  // add the layer to the stage
  stage.add(layer);
}
于 2013-03-07T12:26:05.317 回答