我想在 Adob??e AnimateHTML5Canvas環境下做一個簡單的任務。舞臺上有幾個按鈕,它們旁邊的相應圓形符號實體在開始時是不可見的。當我單擊一個按鈕時,可以看到一個相鄰的圓圈。然后,如果我隨機單擊另一個按鈕,它的相鄰圓圈是可見的,但之前可見的圓圈必須再次變得不可見,因為在任何給定時間應該只有一個圓圈可見。
作為一個簡單的解決方案,我從 4 個實體開始:button_1、button_2、circle_1、circle_2。當我第一次單擊任何按鈕時,我計劃將圓實體的名稱存盤在一個名為“存盤”的變數中。然后將該資訊傳遞給下一個按鈕的滑鼠單擊事件,以使前一個圓形實體再次不可見。我的菜鳥代碼是這樣的……
/*Made circles invisible at the beginning*/
this.circle_1.visible = false;
this.circle_2.visible = false;
/*button's click events*/
var _this = this;
_this.button_1('click', function(){
_this.cicle_1.visible = true;
store.visible = false; /*make the previous circle invisible if any*/
var store = this.circle_1; /*updating current circle's name in variable 'store'*/
});
var _this = this;
_this.button_2.on('click', function(){
_this.circle_2.visible = true;
store.visible = false; /*make the previous circle invisible if any*/
var store = this.circle_2; /*updating current circle's name in variable 'store'*/
});
/* It also works if I can make all circles instances invisible and then show the intended one during every click event, but how can I get and set 20 circle instances invisible in one step? */
但是,代碼不起作用。我沒有編程經驗,所以我的邏輯可能很可笑,但這是我能想到的最簡單的解決方案。也許我應該全域宣告我的變數?任何人都可以改進此代碼或使其作業嗎?請不要For-i或Array解決方案,因為它讓我頭暈目眩:) 提前致謝。
uj5u.com熱心網友回復:
歡迎使用 JavaScript!我可以告訴您您要做什么,但是您犯的一些錯誤對于剛開始犯的人來說很容易。
store在實際使用 宣告變數之前,您正在訪問變數var store = this.circle_1。使用var關鍵字將在其“范圍”的頂部宣告一個變數,無論它宣告了該范圍的哪一行,并將let在您指定的行上宣告它。無論哪種方式,任何變數的存在都不會存在于其范圍之外。范圍由一組花括號組成,{}這意味著您正在宣告store,但是當您離開花括號時,它會立即被洗掉。類似以下內容將解決此問題:
/*
A variable declared in one scope is available to all scopes inside it.
By declaring 'store' outside of any scope/curly braces, it will be accessible from anywhere in the code
*/
var store = this.circle_1; // you store either circle here. I'm just using circle_1 as a placeholder
//rest of code
this.button_1('click', function(){
store.visible = false;
store = this.circle_1;
this.circle_1.visible = true; //make circle 1 visible
});
我覺得你有點想多了(這沒關系,它確實發生了),如果你只有 2 個圓圈,有一種更簡單的方法,我將在下面發布。
您似乎也忘記了事件宣告中的
on關鍵字。this.button_1您正在重新宣告
_this第一次不需要,更不用說兩次了。該代碼var _this = this;將 的參考存盤this在一個名為基本上只是重命名它的新變數中_this,并且不做任何其他事情。
我對 Adob??e Animate 的 JavaScript 風格了解不多,但我會嘗試以我認為應該適用于 Animate 的方式修改您的原始 JavaScript。
如果您只有 2 個圓圈,以下代碼是最簡單的方法
//Made circles invisible at the beginning
this.circle_1.visible = false;
this.circle_2.visible = false;
//button's click events
this.button_1.on('click', function(){
this.circle_1.visible = true; //make circle 1 visible
this.circle_2.visible = false; //make the other circle invisible
});
this.button_2.on('click', function(){
this.circle_2.visible = true;
this.circle_1.visible = false;
});
讓我知道它是否有效,或者如果您在瀏覽器中運行它,請按F12> 單擊Console并讓我知道是否有任何錯誤。
如果您想要任意數量的圓圈,那么您所說的“陣列解決方案”將是最好的。陣列和回圈非常基礎,一旦開始就很容易理解(盡管語法看起來很嚇人)。如果您打算繼續學習編程,那可能應該是您學習的下一件事。
uj5u.com熱心網友回復:
您可能存在可變可見性問題。在函式內宣告 var 不應允許其他代碼段達到該 var 的值。相反,您應該在外面宣告 var 并在那里存盤一個 null,然后呼叫 like if (store) store.visible=false;。因此,只需移動var store兩個函式的外部,并參考store它們兩個內部,就可以了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/418269.html
標籤:
