cocos2d-js 按钮的默认选中状态的简单实现

使用软件,cocos V3.10大集合 Mac系统

需求:同一个界面上三个按钮,每个按钮对应不同的操作,默认显示一个按钮为选中状态,其他两个为未选中状态,操作中点击那个按钮那个为选中状态,其他变为未选中状态

一,首先我们使用cocos新建一个Cocos2d-js的新项目,然后再cocostudio中创建一个场景,在场景中添加三个按钮分别设置三态的图片

cocos2d-js 按钮的默认选中状态的简单实现

 

 

二,打开编辑器,实现代码如下

 1 var HelloWorldLayer = cc.Layer.extend({
 2 
 3     ctor:function () {
 4 
 5         this._super();
 6 
 7         //导入cocostudio中拼好的界面
 8         mainscene = ccs.load(res.MainScene_json).node;
 9         this.addChild(mainscene);
10 
11         this.teamButton = ccui.helper.seekWidgetByName(mainscene,"Button_0");
12         var btn2 = ccui.helper.seekWidgetByName(mainscene,"Button_1");
13         var btn3 = ccui.helper.seekWidgetByName(mainscene,"Button_2");
14 
15 
16 
17          //先默认设置一个按钮为选中状态   this.teamButton.setBrightStyle(ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT);
18         this.teamButton.setEnabled(false);
19         var teamInfo = this.teamButton;
20 
21 
22         this.teamButton.addTouchEventListener(this.selectedBtn1,this);
23         btn2.addTouchEventListener(this.selectedBtn2,this);
24         btn3.addTouchEventListener(this.selectedBtn3,this);
25 
26         return true;
27     },
28 
29     selectedBtn1: function (sender, type) {
30         if(type == ccui.Widget.TOUCH_ENDED){
31             this.callBack(sender);
32             cc.log("==========商店界面");
33         }
34 
35     },
36     selectedBtn2: function (sender, type) {
37         if(type == ccui.Widget.TOUCH_ENDED){
38             this.callBack(sender);
39             cc.log("==========卡牌界面");
40         }
41 
42     },
43     selectedBtn3: function (sender, type) {
44         if(type == ccui.Widget.TOUCH_ENDED){
45             this.callBack(sender);
46             cc.log("==========战斗界面");
47         }
48 
49     },
50 
51     callBack: function (sender) {
52         if (this.teamButton == sender){
53             return;
54         }else{
55             this.teamButton.setBrightStyle(ccui.Widget.BRIGHT_STYLE_NORMAL);
56             this.teamButton.setEnabled(true);
57             sender.setBrightStyle(ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT);
58             sender.setEnabled(false);
59             this.teamButton = sender;
60         }
61     },
62 });
63 
64 
65 
66 var HelloWorldScene = cc.Scene.extend({
67     onEnter:function () {
68         this._super();
69         var layer = new HelloWorldLayer();
70         this.addChild(layer);
71     }
72 });

 

三,运行就可以查看界面,点击不同的按钮显示不同的输出结果

[Log] ==========商店界面 (CCDebugger.js, line 331)
[Log] ==========卡牌界面 (CCDebugger.js, line 331)
[Log] ==========战斗界面 (CCDebugger.js, line 331)

cocos2d-js 按钮的默认选中状态的简单实现

cocos2d-js 按钮的默认选中状态的简单实现

cocos2d-js 按钮的默认选中状态的简单实现