gpt4 book ai didi

javascript - 一个函数对应多个元素

转载 作者:行者123 更新时间:2023-11-28 00:58:12 25 4
gpt4 key购买 nike

我当前正在 Canvas 上绘制元素:

  var head = new Kinetic.Ellipse({
x: stage.width() / 2,
y: 100,
radius: {
x: 50,
y: 60
},
fill: '#DDDDDD',
stroke: 'black',
strokeWidth: 2
});

var neck = new Kinetic.RegularPolygon({
x: stage.width() / 2,
y: 180,
sides: 4,
radius: 70,
fill: '#DDDDDD',
stroke: 'black',
strokeWidth: 2
});

layer.add(neck);
layer.add(head);

并在单击或触摸时更改这些元素的颜色,但我会在屏幕上显示很多元素,并且不希望使用相同数量的功能来更改每个元素。

有没有一种方法可以将下面的两个函数合并为一个函数,但同时影响上面的两个函数。

  head.on('touchstart, mousedown', function() {
var current = this.getFill();
var fill = "";
switch (current) {
case "#DDDDDD":
fill = "#FFC926";
break;
case "#FFC926":
fill = "#FF0000";
break;
case "#FF0000":
fill = "#000000";
break;
default:
fill= "#DDDDDD";
}
this.setFill(fill);
layer.draw();
});

neck.on('touchstart, mousedown', function() {
var current = this.getFill();
var fill = "";
switch (current) {
case "#DDDDDD":
fill = "#FFC926";
break;
case "#FFC926":
fill = "#FF0000";
break;
case "#FF0000":
fill = "#000000";
break;
default:
fill= "#DDDDDD";
}
this.setFill(fill);
layer.draw();
});

最佳答案

您可以提取一个常用函数,并像下面一样使用它

 var evaentListener =  function(obj) {
return function() {
var current = obj.getFill();
var fill = "";
switch (current) {
case "#DDDDDD":
fill = "#FFC926";
break;
case "#FFC926":
fill = "#FF0000";
break;
case "#FF0000":
fill = "#000000";
break;
default:
fill= "#DDDDDD";
}
obj.setFill(fill);
layer.draw();
}
}

head.on('touchstart, mousedown',evaentListener(this));

neck.on('touchstart, mousedown',evaentListener(this));

关于javascript - 一个函数对应多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25976503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com