對 Web 開發行業來說非常陌生,并且在弄清楚我的代碼有什么問題時遇到了一些麻煩。嘗試使用 Divi 在 Wordpress 的代碼片段上實作 javascript,但似乎無法理解到底是什么問題。我的意圖是在單擊時更改按鈕的背景和文本顏色。我會很感激幫助!
<button onClick="firstFunc()";
class="butCol";
style="background-color: transparent;
border: none;
font-weight: bold;
border-radius: 25px;
padding: 2px 15px";>LATTES</button>
<script>
function firstFunc() {
var x = document.getElementByClass("butCol");
if (x.style.backgroundColor == "transparent";) {
x.style.backgroundColor = "#373975";
x.style.color = "white"};
else {
(x.style.backgroundColor = "transparent")
};
};
</script>
uj5u.com熱心網友回復:
這個問題是由一些錯別字引起的。不幸的是,許多人渴望在評論中列出它們。因此,如果這為您解決了問題,請自愿洗掉您的問題:
if (x.style.backgroundColor == "transparent";) {-> 洗掉分號:if (x.style.backgroundColor == "transparent") {x.style.color = "white"};-> 交換分號和夾子:x.style.color = "white"; }(x.style.backgroundColor = "transparent")-> 移除夾子并以分號結尾:x.style.backgroundColor = "transparent";- 沒有
getElementByClass正義getElementsByClassName。但是,這將回傳一個陣列。改用就好querySelector了。
function firstFunc() {
var x = document.querySelector(".butCol");
if (x.style.backgroundColor == "transparent") {
x.style.backgroundColor = "#373975";
x.style.color = "white";
} else {
x.style.backgroundColor = "transparent";
};
};
<button onClick="firstFunc()";
class="butCol";
style="background-color: transparent;
border: none;
font-weight: bold;
border-radius: 25px;
padding: 2px 15px";>LATTES</button>
然而,更聰明的是使用 CSS 來應用更改并僅使用該.classList.toggle('class-name');函式:
function firstFunc() {
document.querySelector('.butCol').classList.toggle('clicked');
}
.butCol {
background-color: transparent;
border: none;
border-radius: 25px;
padding: 2px 15px;
font-weight: bold;
}
.clicked {
background-color: #373975;
color: white;
}
<button onClick="firstFunc()";
class="butCol";>LATTES</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/477024.html
標籤:javascript html css WordPress 迪维
