我一直在嘗試使用 js .toggle 功能來更改鏈接的類,以將其從一種顏色變為另一種 onclick。
<html>
<style>
.the-button-inactive {
display: inline-block;
height: 20px;
width: 20px;
border-radius: 10px;
background-color: black;
}
.the-button-active {
display: inline-block;
height: 20px;
width: 20px;
border-radius: 10px;
background-color: blue;
}
</style>
<body>
<div class="the-button-container">
<a href="#the-image-1" id="the-image-1-id" onclick="myFunction()" class="the-button-inactive"></a>
</div>
<script>
function myFunction() {
var element = document.getElementByID("the-image-1-id");
element.classList.toggle("the-button-active");
}
</script>
</body>
</html>
該鏈接已經具有“ the-button-inactive”類,我正在嘗試the-button-active使用上述腳本將其切換為“”類單擊,但我不確定它為什么不起作用。最終目標是讓鏈接在單擊時將顏色從黑色變為藍色,然后在單擊另一個鏈接時再次從藍色變為黑色。
到目前為止,單擊鏈接時沒有任何反應。
我以前可以使用按鈕而不是鏈接來實作這一點,但現在決定嘗試使用鏈接來解決這個問題。
這是我用來測驗這個腳本的 jsfiddle:https ://jsfiddle.net/tqr2h4pb/
uj5u.com熱心網友回復:
您的代碼中有錯字。更改getElementByID為getElementById,它作業正常。
你應該經常檢查控制臺是否除錯它說Uncaught TypeError: document.getElementByID is not a function"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/495392.html
標籤:javascript html css
