JavaScriptを使用して背景色を切り替える
-
10-07-2019 - |
質問
次のコードがここで定義された色の配列を循環しない理由を教えてください:
var colors = ["white", "yellow", "orange", "red"];
そしてここに問題のコード行があります:
setInterval(function(){
currElm.style.background = colors[(nextColor++)%(colors.length)]);
}, 500);
それはうまくいくようで、このようなコードがカラーサイクリング効果を生むいくつかの例を見てきました。上の(または下の)コードに問題がありますか?
機能全体(進行中の作業):
function setHighlight(elmId, index, songLength){
//alert("called set highlight, params are " + elmId + " " + index + " " + songLength);
var colors = ["white", "yellow", "orange", "red"];
var nextColor = 0;
if(index < 10)
index = "000" + (index);
else if (index < 100)
index = "000" + (index);
else if(index < 1000)
index = "0" + (index);
if(index >= 1000)
index = index;
//alert("called set highlight, params are " + elmId + " " + index + " " + songLength);
//this will be useful for finding the element but pulsate will not work, need to research animations in javascript
var mainElm = document.getElementById('active_playlist');
var elmIndex = "";
for(var currElm = mainElm.firstChild; currElm !== null; currElm = currElm.nextSibling){
if(currElm.nodeType === 1){
var elementId = currElm.getAttribute("id");
if(elementId.match(/\b\d{4}/)){
elmIndex = elementId.substr(0,4);
alert(currElm.getAttribute('id'));
if(elmIndex == index){
setInterval(function(){
currElm.style.background = colors[(nextColor++)%(colors.length)]);
}, 500);
}
}
}
}//end for
}
すべてのヘルプは大歓迎です。ありがとう
解決
いくつかの異なるもの。まず、IDにスペースが含まれ、その後に4桁の数字が含まれる要素に一致しているように見えます。 idにスペースが許可されているとは思わない。一致する必要がある要素のHTMLを本当に見たいです。 2つ目は、setIntervalハンドラーでキャプチャされる新しい変数にcurrElmを割り当てたいと思うことです。そうしないと、一致する各要素ではなく、最後に一致した要素を常に参照する可能性があると思います。
for(var currElm = mainElm.firstChild; currElm !== null; currElm = currElm.nextSibling){
if(currElm.nodeType === 1){
var elementId = currElm.getAttribute("id");
if(elementId.match(/\b\d{4}/)){
elmIndex = elementId.substr(0,4);
alert(currElm.getAttribute('id'));
if(elmIndex == index){
var that = currElm;
setInterval(function(){
that.style.background = colors[(nextColor++)%(colors.length)];
}, 500);
}
}
}
}//end for
編集間隔ハンドラーの余分な括弧も修正します。
他のヒント
構文エラー、行末の余分な右括弧 ')'
:
currElm.style.background = colors[(nextColor++)%(colors.length)]);
余分な右括弧も表示されます!
ただし、nextColor変数は、colors配列の直後で既にゼロに初期化されています。
これはFirebugの仕事です。 setInterval呼び出しに到達する直前にブレークポイントを設定し、setIntervalの匿名関数にあるさまざまな変数をテストできます。
所属していません StackOverflow