我有一个基本的flash文档,显示了几周内的足球比赛。我每周都有按钮,例如"游戏周1"、"游戏周2"等。
按下按钮时,按钮下方会显示一个电影剪辑,用于显示固定装置。固定装置电影剪辑始终在那里,但按钮会将其更改为可见。
我的问题是……如果我显示了游戏周1的固定装置,然后我点击"游戏周2"按钮,两组固定装置都会显示,因为游戏周1固定装置仍然可见。
当我按下一个按钮来显示新的固定装置时,我希望以前可见的电影剪辑现在是不可见的,这样只有新固定装置才可见。
这是我的动作脚本:
stop();
btn_game1.addEventListener(MouseEvent.CLICK,openGame1);
function openGame1(evt:MouseEvent) {
if (game1.visible){
game1.visible = false;
}else {
game1.visible = true;
}
}
btn_game2.addEventListener(MouseEvent.CLICK,openGame2);
function openGame2(evt:MouseEvent) {
if (game2.visible){
game2.visible = false;
}else {
game2.visible = true;
}
}
我想提出一种重新分解的方法,减少代码量和事件处理程序的数量。
对于所有的按钮,您只需要一个按钮处理程序。您还需要跟踪正在显示/隐藏的所有剪辑。它们可以存储在一个数组中。
您可以通过给按钮起相似的名称(btn_game1
和game1
)将其"连接"到剪辑。
以下代码假设您的按钮都命名为btn_gameN
,剪辑命名为gameN
(其中N是一个数字):
var clips:Array = [game1, game2, game3, game4];
btn_game1.addEventListener(MouseEvent.CLICK, onGameButtonClicked);
btn_game2.addEventListener(MouseEvent.CLICK, onGameButtonClicked);
btn_game3.addEventListener(MouseEvent.CLICK, onGameButtonClicked);
btn_game4.addEventListener(MouseEvent.CLICK, onGameButtonClicked);
function onGameButtonClicked(e:MouseEvent):void
{
// figure out which button was just clicked by looking at its name
var clipNum:String = e.currentTarget.name.substr("btn_game".length);
// loop through all of your clips ...
for each(var clip:MovieClip in clips)
{
if(clip.name.substr("game".length) == clipNum)
{
// if the name matches, toggle the visibility
clip.visible = !clip.visible;
}
else
{
// if the name doesn't match, set visibility to false
clip.visible = false;
}
}
}
显示game1
时,必须隐藏game2
。CCD_ 7也是如此。
function openGame1(evt:MouseEvent) {
if (game1.visible) {
game1.visible = false;
}else {
game1.visible = true;
game2.visible = false;
}
}