我想在用戶單擊頁面頂部的按鈕(單擊此處更改正文背景的顏色)時更改正文的背景;這是頁面:https : //relaxed-ardinghelli-701d99.netlify.app/ 我只成功做到了一次;我使用了 for 回圈,所以相同的代碼被執行了 10 或 20 次......但它不起作用:
for(let i=0; i<100; i ){
bg_button.addEventListener("click", funct2);
function funct2(e) {
body.style.backgroundColor = "lightgrey"
section_top.style.backgroundColor="white"
bg_button.addEventListener("click", funct3);
function funct3(e) {
body.style.backgroundColor = "white"
section_top.style.backgroundColor=""}}}
uj5u.com熱心網友回復:
如果您想更改按鈕單擊時的背景顏色,您應該使用 JavaScript 函式并更改 HTML 頁面中的樣式。
function chBackcolor(color) {
document.body.style.background = color;
}
它是 JavaScript 中用于更改顏色的函式,您將在事件中呼叫此函式,例如:
<input type="button" onclick="chBackcolor('red');">
如果你只想要幾秒鐘,你可以使用 setTimeout 函式:
window.setTimeout("chBackColor()",10000);
uj5u.com熱心網友回復:
如果您希望按鈕無論單擊多少次都切換背景顏色,則可以在更新狀態變數的單個事件偵聽器中執行此操作:
let toggleState = false
function toggleBackground() {
toggleState = !toggleState
if (toggleState) {
body.style.backgroundColor = "lightgrey"
section_top.style.backgroundColor="white"
} else {
body.style.backgroundColor = "white"
section_top.style.backgroundColor=""
}
}
bg_button.addEventListener("click", toggleBackground);
或者您可以替換事件偵聽器,而不是在單擊時添加一個新的偵聽器:
function setBg1() {
body.style.backgroundColor = "lightgrey"
section_top.style.backgroundColor="white"
bg_button.onclick = setBg2
}
function setBg2() {
body.style.backgroundColor = "white"
section_top.style.backgroundColor=""
bg_button.onclick = setBg1
}
bg_button.onclick = setBg1
uj5u.com熱心網友回復:
您好,您可以使用以下功能:
function bgColorToggle () {
const availableColors = ['blue','red'];
for(int i=0;i<100;i ) {
let color = availableColors[i%2];
setTimeout((document.body.style.color = color),2000);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355932.html
標籤:javascript
