如何使用组上的鼠标悬停/鼠标移出事件处理填充切换

How to handle fill toggle with mouseover / mouseout events on group

在 jquery 中,我们对此进行了切换。

如果我这样做 jquery DIY,我会将 'on' 和 'off' 填充颜色存储在元素的 'data' 属性中,并根据需要检索每个颜色。

在 Konva 中实现鼠标悬停填充颜色切换的有效方法是什么?

示例:假设我有一个层,在这个层上我有一个包含矩形的组。鼠标悬停和鼠标移出切换通过在鼠标悬停时更改其填充颜色并在鼠标退出时恢复正常来突出显示矩形可能是

rect.on('mouseover', function(evt){
  var shape = evt.target;
  // Uh-oh, I need to stash the current fill color somewhere 
  shape.fill('lime');

})
rect.on('mouseexit', function(evt){
  var shape = evt.target;
  shape.fill('that_stashed_fill_color');  // < how to get the stashed val and from where ?
})

有什么想法吗?

编辑:我自己的尝试是使用

rect.on('mouseover', function(evt){
  var shape = evt.target;
  $(shape).data('bgColor', shape.fill()); // stash current in data
  shape.fill('lime');    
})

rect.on('mouseexit', function(evt){
  var shape = evt.target;
  shape.fill($(shape).data('bgColor'));  // get the stashed val from jq data
})

这可行,但使用 jq 包装器感觉像是一种我希望避免的开销。

您几乎可以在 Konva 节点中使用任何自定义属性(确保您不与现有属性重叠,以免出现意外结果)。设置 - shape.setAttr('anyAttibute', anyValue); 得到 - shape.getAttr('anyAttibute');

你可以这样做:

rect.on('mouseenter', function(evt){
  var shape = evt.target;
  shape.setAttr('oldFill', shape.fill());
  // set new fill
  shape.fill('lime');
  shape.getLayer().batchDraw();
})
rect.on('mouseleave', function(evt){
  var shape = evt.target;
  shape.fill(shape.getAttr('oldFill')); 
  shape.getLayer().batchDraw();
})

但我个人更喜欢使用这个:


const FILL_COLOR = 'red';
const HIGHLIGHT_COLOR = 'lime';

shape.fill(FILL_COLOR);
shape.on('mouseenter', function(evt){
  shape.fill(HIGHLIGHT_COLOR);
})
shape.on('mouseleave', function(evt){
  shape.fill(FILL_COLOR); 
})