這個問題是從超級用戶遷移過來的,因為它可以在 Stack Overflow 上回答。 8 小時前遷移 。
因此,如果我將滑鼠放在“更改”按鈕上,橙色懸停顏色將正常作業。
如果我單擊“更改”按鈕一次,顏色變為紅色但懸停顏色消失(沒關系)。
如果我按 2 次,它會回傳第一種顏色(藍色),但懸停顏色不起作用。
懸停顏色如何在第一次點擊時消失(就像現在一樣)并在第二次點擊時重新出現,就像在開始時一樣?非常感謝!!!
var someFunction = {};
function changeColor() {
var button = document.getElementById('mute1').style.backgroundColor;
var color = '';
this.active = !this.active;
someFunction["one"] = this.active;
someFunction["two"] = this.active;
if (button !== 'red') {
color = 'red';
document.getElementById('mute1').style.backgroundColor = color;
document.getElementById('mute1').style.color = "#fff";
} else if (button === 'red') {
color = '#2c475c';
document.getElementById('mute1').style.backgroundColor = color;
document.getElementById('mute1').style.color = "#fff";
this.active = !this.active;
someFunction[this.function] = this.active;
}
}
#mute1 {
padding: 25px 50px;
background: #2c475c;
color: #fff;
border-radius:5px;
}
#mute1:hover {
background: orange;
}
<button id="mute1" onclick="changeColor();">CHANGE</button >
uj5u.com熱心網友回復:
問題是懸停僅通過類更改顏色,而單擊更改行內樣式并且優先。如果您使用瀏覽器開發工具查看,您會看到在您完成第一次點擊后,該元素設定了行內背景樣式。
如果您想停止并始終懸停使背景顏色為橙色,您有幾種選擇:
堅持在單擊時更改行內樣式,但還要在 JS 中為滑鼠懸停添加一個事件偵聽器,將行內背景更改為橙色或
一切都使用類。
此代碼段洗掉了懸停類,而是偵聽 mouseenter 和 mouseout 事件以及單擊按鈕。
它使顏色變數全域化,以便它也可以在 mouseout 事件代碼中使用,以恢復之前存在的顏色(紅色或灰色)。
這里的代碼相當基本,就在按鈕內,您可能希望將其變成“正確的”JS 函式,并且還需要添加事件監聽器而不是使用行內的 onclick 等屬性。
let color = '#2c475c';
var someFunction = {};
function hovered() {}
function changeColor() {
var button = document.getElementById('mute1').style.backgroundColor;
/*var */
color = '';
this.active = !this.active;
someFunction["one"] = this.active;
someFunction["two"] = this.active;
if (button !== 'red') {
color = 'red';
document.getElementById('mute1').style.backgroundColor = color;
document.getElementById('mute1').style.color = "#fff";
} else if (button === 'red') {
color = '#2c475c';
document.getElementById('mute1').style.backgroundColor = color;
document.getElementById('mute1').style.color = "#fff";
this.active = !this.active;
someFunction[this.function] = this.active;
}
}
#mute1 {
padding: 25px 50px;
background: #2c475c;
color: #fff;
border-radius: 5px;
}
<button id="mute1" onclick="changeColor();" onmouseenter="this.style.backgroundColor = 'orange';" onmouseout="this.style.backgroundColor = color;">CHANGE</button >
uj5u.com熱心網友回復:
<button id="mute1" onclick="changeColor()">CHANGE</button >
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/355511.html
標籤:html javascript css 查询
